【问题标题】:Values are not passed from the method in component to the html template in Angular5. (*ngIf is not working)值不会从组件中的方法传递到 Angular 5 中的 html 模板。(*ngIf 不起作用)
【发布时间】:2019-04-20 18:31:53
【问题描述】:

我正在尝试从父组件调用子组件的函数。

Parent.component.html

<div class="collapse list-unstyled">
<div *ngFor="let data of data1; let i=index">
<li>
<a  class="dropdown-item menu-item" (click)= callchild(i)  >
                                {{data.item}} 
</a>
</li>
</div>

Parent.component.ts

export class ParentComponent implements OnInit {

constructor(  private child: ChildComponent) { }

callchild(i){
this.child.menu(i);

}

从 parent.component.html 我正在调用函数 callchild(i),它是 parent.component.ts 中存在的函数。从这个组件中,我正在调用作为子组件一部分的功能 menu(i)。

Child.component.ts

menu(i){
this.visible = true;
}

在这个 menu(i) 函数中,我将 visible 的值设置为 true。

Child.component.html

   <div class="row"  *ngIf="visible; then item1"> 
   </div> 
   <ng-template #item1 >

   </ng-template>

将 visible 的值设置为 true 后,我希望看到 ng-template 中的内容。但它没有加载。 如果我从 Child.component.html 调用 menu(i),那么它会成功加载 ng-template 中的内容。但我想从父组件调用 menu(i),然后加载子组件的内容。 谁能告诉我我做错了什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

    也许像@ViewChildren 之类的?

    @Component({
        selector: 'app-child',
        templateUrl: '<div > content here <div *ngIf="isVisible"> will show on click</div> </div>',
        styleUrls: ['./child.component.scss']
    })
    export class ChildComponent implements OnInit {
        isVisible=false
    }
    
    
    @Component({
        selector: 'app-parent',
        template: '<app-child *ngFor="let item of items" (click)="setVisible(item)"></app-child>',
        styleUrls: ['./parent.component.scss']
    })
    export class ParentComponent implements OnInit {
        @ViewChildren(ChildComponent) itemsList: QueryList<ChildComponent>;
        items;
        setVisible(item){
          this.itemsList.forEach((it) => {
            if(it.id === item.id){ // <== or whatever strategy you need here
                it.isVisible = true;
            }
          })
       }
    }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多