【问题标题】:Angular4: Component reference inside ng-templateAngular4:ng-template 中的组件引用
【发布时间】:2017-08-14 15:24:35
【问题描述】:

我是 Angular 4 的新手。 我想在 ng-template 中处理一个组件(validation-alerts)

<ng-template #content let-c="close" let-d="dismiss" size="600px" >  
    <validation-alerts  [formGroup]="requestTypeForm"></validation-alerts>  
    <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix head" tabindex="-1">
        <span id="ui-id-6" class="ui-dialog-title popup-title">Client Name Look Up </span>
        <button (click)="d('Cross click')" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" 
        role="button" aria-disabled="false" title="Close">
        <span class="ui-button-icon-primary ui-icon ui-icon-closethick popup-close-icon"></span><span class="ui-button-text">Close</span>
        </button>
    </div>
    <form (ngSubmit)="onSubmit()" [formGroup]="requestTypeForm">
    <div id="scrollContainer-popup" class="popup ui-dialog-content ui-widget-content" style="width: auto; min-height: 0px; max-height: none; height: auto; display: block; padding: 0px 10px 0px">
        <div class="body">
            <p class="mb"><b>Select the matching client name:</b></p>
            <input type="text" formControlName="clientId" name="clientId" 
                    id="clientId" style="width:30%" />

            <div class="btnBar nbdr" style="padding-top: 0px;" >
                <a (click)="c('close')" class="btn3"><span>Cancel</span></a>      
                <button type="button" class="btn" (click)="c('submit')">Select</button>  
            </div>
        </div>
    </div>
    </form> 
</ng-template>

我尝试使用 @ViewChild、@ViewChildren 但在 AfterContentInit 方法中未定义。

 @ViewChild(ValidationAlertsComponent)
  private validationAlerts: ValidationAlertsComponent;

组件类

@Component({
  selector: 'provision-modal',
  templateUrl: 'provision.modal.html',
  encapsulation: ViewEncapsulation.None,
  styles : [ '.namelookup .modal-content {  width: 600px;}']
 })
export class ProvisionModal implements AfterContentInit {
  @ViewChild('content')  contentTemplate: TemplateRef<any>;

   @ViewChild(ValidationAlertsComponent)
  private validationAlerts: ValidationAlertsComponent;

     ngAfterContentInit() {
     console.log('Ng after content init '+ this.validationAlerts);
  }

【问题讨论】:

  • 请多发些组件类代码
  • 组件类代码添加
  • validationAlerts 未定义
  • 你在provisionModal组件中导入validationAlerts组件了吗?
  • 是的,我已经导入了validationAlerts

标签: angular


【解决方案1】:

您应该在 ngAfterViewInit 生命周期钩子之后访问子视图。

https://angular.io/guide/lifecycle-hooks

所以改变

ngAfterContentInit() {
     console.log('Ng after content init '+ this.validationAlerts);
}

ngAfterViewInit() {

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-10-01
    • 2018-09-02
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多