How do I combine a template reference variable with ngIf?

后端 未结 5 828
抹茶落季
抹茶落季 2020-12-14 06:16
tRefVar is {{tRefVar.foo}}

Even though the

5条回答
  •  鱼传尺愫
    2020-12-14 07:06

    You could use for example ng-container and set your ngIf conditional there, which makes tRevVar accessible like this:

    
         

    Hello {{name}}, tRefVar is {{tRefVar.foo}}

    tRefVar is {{tRefVar?.foo}}

    Plunkr: https://plnkr.co/edit/cqrsDVGwa90o1FGWgE22?p=preview

    There are probably more ways to make it work, but you have to be more specific then, what you want to do with it.

    Hope i could help.


    To answer the question in your comment "Shouldn't it update tRefVar after that first tick though?":

    No, because it's undefined. You'll have the same outcome if you declare an object in your component (but leave it undefined) and add a property to it. The elvis operator doesn't help there.

    myObj: any;
    
    ngOnInit() {
        myObj.text = 'my Text';
    }
    
    
    {{ myObj?.text }}

    This won't work, but this would be working:

    myObj: any = {};
    
    ngOnInit() {
        myObj.text = 'my Text';
    }
    
    
    {{ myObj?.text }}

    Edited my answer again and removed the confusing explanation which was plain wrong. thanks yurzui, finally got what you meant. needed a night of sleep for it.

提交回复
热议问题