代码之家  ›  专栏  ›  技术社区  ›  Fallenreaper

viewchild为空,因为它不在dom(ngif)中,是否有方法在找到函数时编写要运行的函数?

  •  1
  • Fallenreaper  · 技术社区  · 6 年前

    我的设计:

    我有一个标签,它利用了ngif,所以子内容不在dom中。问题是内部组件需要设置订阅。有没有一种方法可以让我的viewchild在不为空时运行函数?

    @ViewChild("fooId")
    MyCustomClass foo;
    
    StreamSubscription sub = null;
    

    对我来说,我在想我需要做某种while循环,并延迟定期检查foo以查看它是否不为空。

    setUp() async {
      while(sub == null){
        if (foo != null){
           sub = foo.onChanged.listen((_)=>_func());
        }
        await new Future.delayed(new Duration(seconds: 1));
      }
    }
    

    但看起来有点脏。

    是否可以在init文件中设置类似于以下内容的操作:

    ngOnInit(){
      // foo.when( () => foo !=null, (){ 
      //   sub = foo.onChanged.listen((_)=>_func());
      // });
    }
    

    很明显,这是伪代码,但我认为有比某些轮询代码更好的选择来保持检查空性。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Günter Zöchbauer    6 年前

    制作 foo 设置者:

    MyCustomClass _foo;
    
    @ViewChild("fooId")
    set foo(MyCustomClass value) {
      _foo = value;
      ...
    }