0

我有以下场景......

// child-component.ts
@Input() attrOne: any;
@Input() attrTwo: any;
isVisible: boolean = true;

HideThis(){
  this.isVisible = false;
}

和...

// child-component.html
<div *ngIf="isVisible">
  <!-- nested content -->
  <span (click)="HideThis()">Hide This</span>
</div>

然后...

// parent-component.html
// listData comes from server as is...
<ng-container *ngFor="let item of listData">
  <child-component [attrOne]="item.propOne" [attrTwo]="item.propTwo"></child-component>
</ng-container>

一个子组件,我们称之为child-component,嵌入在parent-component中。我在父组件上使用 ng-for来使用嵌入的子组件列出数据数组...我需要能够在任何嵌入的子组件上执行(click)="HideThis()"。 .. 我的尝试(如上)隐藏了内容,但是当我单击 HideThis() 时,在父组件的 DOM 中留下了一个空白的子组件元素。我希望完全删除或避免列出相应的子组件。

我不能使用 listData[n].item.prop 之类的属性来进行 *ngIf 测试。listData 来自远程服务器。有没有办法避免使用类似的东西@Output() onHidden: EventEmitter<any> = new EventEmitter<any>();

我尝试过ng-templateng-content无济于事。最好的方法是什么?

4

2 回答 2

0

如果您需要<app-child>从 DOM 中完全删除选择器,则条件应包含在父组件中,而不是子组件中。

父组件.ts

listData: {propOne: string, propTwo: string, visible: boolean}[];

ngOnInit() {
  this.someService.getList().pipe(
    map(response => { response.forEach(item => item['visible'] = true })
  ).subscribe(
    list => { this.listData = list },
    error => { }
  );
}

父组件.html

<ng-container *ngIf="listData">
  <ng-container *ngFor="let item of listData">
    <ng-container *ngIf="item.visible">
      <app-child [attrOne]="item.propOne" [attrTwo]="item.propTwo"></app-child>
      <button (mouseup)="item.visible = false">Click here to hide</button>
    <ng-container>
  </ng-container>
</ng-container>

现在isVisible子组件中不再需要该属性。

如果单击它,这自然会永远隐藏子组件。您可以将其更改为切换功能,方法是将按钮向外移动一层,并在回调中切换标志而不是将其设置为false.

<ng-container *ngIf="listData">
  <ng-container *ngFor="let item of listData">
    <ng-container *ngIf="item.visible">
      <app-child [attrOne]="item.propOne" [attrTwo]="item.propTwo"></app-child>
    <ng-container>
    <button (mouseup)="item.visible = !item.visible">Click here to hide</button>
  </ng-container>
</ng-container>
于 2020-06-15T11:43:28.677 回答
0

您可以将 *ngFor 放在组件本身上,而无需额外的包装:

<child-component *ngFor="let item of listData" [attrOne]="item.propOne" [attrTwo]="item.propTwo"></child-component>

我不能使用像 listData[n].item.prop 这样的属性

实际上你可以这样做:

<child-component *ngFor="let item of listData" [attrOne]="item.propOne; let i = index" [attrTwo]="item.propTwo"></child-component>

但不要认为这是正确的方法

如果您需要更详细的答案 - 请为其创建一个 stackblitz 沙箱

于 2020-06-15T11:33:55.470 回答