【问题标题】:How do I dynamically remove and add back component in angular2?如何在 angular2 中动态删除和添加回组件?
【发布时间】:2016-10-20 20:51:20
【问题描述】:

我有一个定义为“FancyButton”的组件。我在模板里有它:

...
<div class="container">
  <div class="fancy">
    <fancybutton></fancybutton>
  </div>
  <button (click)="removeFancyButton">Remove</button>
  <button (click)="addFancyButton">Add</button>
</div>
...

我的问题是,如何以编程方式删除:

  <div class="fancy">
    <fancybutton></fancybutton>
  </div>

当我点击删除按钮时?相反,我如何将其添加回来?如果可能,我希望它触发 ngOnDestroy,如果它“重新添加”,则在重新添加时触发 ngOnInit。

这是我的花式按钮组件,下面是我在 home.component.html 中集成了花式按钮的父模板:

@Component({
  selector: 'fancy-button',
  template: `<button>clickme</button>`
})
export class FancyButton {}

@Component({
  selector: 'home',  // <home></home>
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})

【问题讨论】:

    标签: angular


    【解决方案1】:

    试一试*ngIf,它会在不应该显示的时候删除dom元素,反之则添加dom元素

    根据 {expression} 删除或重新创建 DOM 树的一部分。

    ...
    <div class="container">
      <div *ngIf="showButton" class="fancy">
        <fancybutton></fancybutton>
      </div>
      <button (click)="removeFancyButton">Remove</button>
      <button (click)="addFancyButton">Add</button>
    </div>
    ...
    
    @Component({
      selector: 'home',  // <home></home>
      providers: [
        Title
      ],
      styleUrls: [ './home.component.css' ],
      templateUrl: './home.component.html',
      directives: [FancyButton],
    })
    export class Home {
        showButton: Boolean = true;
    
        addFancyButton() {
            // Do everything you need to
            this.showButton = true;
        }
        removeFancyButton() {
            // Do everything you need to
            this.showButton = false;
        }
    }
    

    【讨论】:

      【解决方案2】:

      声明一些组件属性,例如 isFancyBtnVisible = true 并在点击时更改它。然后在你的按钮组件上使用 *ngIf="isFancyBtnVisible"

      【讨论】:

        【解决方案3】:

        如果你使用 *ngIf,它会在 true 时调用 ngOnOnit,在 false 时调用 ngOnDestroy。

        &lt;fancy-button *ngIf="showButton"&gt;&lt;/fancy-button&gt;

        【讨论】:

          【解决方案4】:

          您只能以命令方式删除以命令方式添加的组件。有关示例,请参见 Angular 2 dynamic tabs with user-click chosen components。否则使用*ngIf="expr"。如果表达式为假,则删除内容。

          【讨论】:

            猜你喜欢
            • 2017-12-09
            • 2017-02-02
            • 2011-11-10
            • 1970-01-01
            • 2017-01-16
            • 2016-10-20
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多