【问题标题】:How to pass component reference in Input with *ngIf Angular2如何使用 *ngIf Angular2 在 Input 中传递组件引用
【发布时间】:2016-12-14 05:03:13
【问题描述】:

我在 Angular2 中有 2 个同级组件:

<test1 *ngIf="data"  [data] = "makes" #test1R></formModel>
<testing *ngIf="data" [test1Ref]="test1R"></testing>

组件“Testing”有一个调用test1组件函数的函数:

export class Testing{

    @Input() test1Ref: test1Component;
    constructor() { }

    testFunction($event){
        this.test1Ref.hello();
    }

我的问题是 this.test1Ref 未定义,因为 test1 组件有 *ngIf (&lt;test1 *ngIf="data") ,
但没有 *ngIf 我在输入值的 test1 组件中有错误 ([data] = "makes")。
如何使用 *ngIf 传递组件引用

【问题讨论】:

    标签: angular


    【解决方案1】:

    简而言之,你不能。如果 !data ,则必须隐藏组件,这样您的局部变量 #test1R 仍将被设置。

    <test1 [hidden]="!data" [data]="makes" #test1R></test1>
    

    然后在 ngOnInit() 中的 test1 内部检查 null 以避免异常。

    如果您只能在设置数据后执行某些代码,请这样做:

    在 test1 组件中将数据声明为输入:

    export class Test1 {
      @Input() data: any;
    }
    

    通过将其声明为@Input,每次值更改时,Angular 都会调用 ngOnChanges,所以现在您可以这样做:

    ngOnChanges(changes: SimpleChanges) {
      if(changes['data'] && changes['data'].currentValue) {
        //Do something once data is set.
      }
    }
    

    【讨论】:

    • 哦,我明白了,我不喜欢,因为如果我使用异步调用检索数据,检查 ngInit 中是否存在数据总是无用的..所以我必须处理一些事件?
    • 更新了答案以显示如何处理异步空值检查。
    • 没有问题 :-) 玩得开心!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2017-01-15
    • 2017-04-30
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多