【问题标题】:Angular 5 - onclick event append component into divAngular 5 - onclick 事件将组件附加到 div
【发布时间】:2017-11-27 14:00:45
【问题描述】:

我正在使用 Angular 5,我有这个:

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  appendToContainer() {
    // Do the stuff here
    // Append PanelComponent into div#container
  }

}

现在是 app.component.html

// app.component.html
<button (click)="appendToContainer()"></button>
<div id="container"></div>

最后我有一个简单的组件

// panel.component.html
<div class="panelComponent">
  This is a panel Component html
</div>

我想要做的是每次点击 app.component.html 上的按钮时,我需要一个 panel.component 附加到 app.component.html

我该怎么做?

【问题讨论】:

  • 我感觉你从错误的角度看待这个问题。你不应该用*ngFor 迭代一个数组吗?
  • 您可以在调用appendToContainer 时使用可以附加到的对象数组,并使用*ngFor 为数组中的每个项目创建一个面板
  • 我想要做的是在组件上创建一个新实例并在单击按钮时将其附加到 div 中
  • @pedromartinez 你找到解决方案了吗?

标签: javascript angular angular5


【解决方案1】:

你可以使用 *ngFor 和一个变量来实现你想要的

//In your component
num:number=0

//You html like 
<button (click)="num++"></button>
//we create a array "on fly" and slice to get only a "num" items
<div *ngFor="let item in [0,1,2,3,4,5,6,7,8,9].slice(0,num)" class="panelComponent">
  This is a panel Component html
</div>

【讨论】:

  • 我想要做的是在组件上创建一个新实例并在单击按钮时将其附加到 div 中
  • 似乎那里的代码不适用于 Angular 5。这是我的 app.component.ts: import { Component } from '@angular/core';从'./child/child.component'导入{ ChildComponent }; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) 导出类 AppComponent { constructor() {} addCmp( ) { 控制台.log('添加'); // 添加 ChildComponent 的实例 } }
猜你喜欢
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
相关资源
最近更新 更多