点击时附加角度分量

问题描述 投票:-3回答:2

我想在点击按钮时使用类myBLock在div中添加一个组件

code:
<div class="myExample">
    <button (click)="addComponent()">
    </button>
</div>
<div class="myBlock">
</div>
angular angular-components
2个回答
1
投票

如果要添加html:

HTML

<div class="myBlock" #block>
</div>

在组件中:

@ViewChild('block') block:ElementRef;

addComponent() {
  block.nativeElement.insertAdjacentHTML('beforeend', '<div></div>');
}

如果要添加组件,则需要动态执行此操作:

https://angular.io/guide/dynamic-component-loader


0
投票

您可以根据按钮单击将组件变量设置为true / false。然后根据变量值显示/隐藏组件。

<div>
  <button (click)='showMyBlock = !showMyBlock'>
  </button>
</div>

<another-component *ngIf='showMyBlock'>
</another-component>
© www.soinside.com 2019 - 2024. All rights reserved.