您已经有一个正在触发的事件完全符合您的需要:“打开” div 的单击。除了在模板中设置 isCollapsed 变量之外,您还可以像这样调用那里的函数:
模板
<div class="row table-dark table-bordered">
<div class="col-xl-12" (click)="toggleOpenMyDiv()">
Click Me!
<ng-container *ngIf="isCollapsed;">
<div class="col-xl-12" id="test"></div>
Open
</ng-container>
</div>
</div>
component.ts
// Call this method to open/close your div
toggleOpenMyDiv() {
this.isCollapsed = !this.isCollapsed; // set the variable
if (this.isCollapsed) {
this.test(); // Then call test
}
}
test() {
console.log("is work");
// You should not do the following lines in angular (it works but is a very bad practice!)
const firstRow = document.createElement('div');
firstRow.innerText = 'Eureka';
firstRow.style.color = 'red';
document.getElementById('test').appendChild(firstRow);
}
此外,我强烈建议不要像在 test() 方法中尝试那样手动创建 HTML 元素。您可以通过在 HTML 中使用 Bindings 让 Angular 为您完成这项工作。
例如,如果您尝试在打开时添加行:
模板
<div class="row table-dark table-bordered">
<div class="col-xl-12" (click)="toggleOpenMyDiv()">
Click Me!
<ng-container *ngIf="isCollapsed;">
<div class="col-xl-12" id="test">
<!-- The template for each row, angular will update this for you based on the "rows" variable -->
<div *ngFor="let row of rows" [style.color]="row.color">{{row.text}}</div>
</div>
Open
</ng-container>
</div>
</div>
component.ts
rows = []; // Every row that should be iterated over in the template
// Call this method to open/close your div
toggleOpenMyDiv() {
this.isCollapsed = !this.isCollapsed; // set the variable
if (this.isCollapsed) {
this.test(); // Then call test
}
}
test() {
console.log("is work");
// Add a row to the array, angular will take care of updating the template, just don't mutate the array but create a new one with the modifications
this.rows = [...this.rows, {color: 'red', text: 'Eureka'}];
}
这里是Stackblitz。