在Angular上加载动态div时遇到麻烦。我做了一个按钮,在特定区域的每次单击上都会添加新的div。但是,一旦我添加了它们,就会出现问题,因为它们显示不正确:
添加了div后,编辑器和日历(均由PrimeNG制作)未显示,如上图所示。但是,在文本框中单击两次(在下图中标记为红色)之后,组件加载完毕。
这是我用来演示的HTML代码。
<div class="ui-g-9" style="border: 2px solid #c8c8c8; border-radius: 5px;">
<section class="card" style="display: flex; overflow-x: auto; overflow-y: unset;">
<div *ngFor="let disparaEmail of disparaEmails" class="ui-g-4" style="margin-right: 10px; border: 1px solid #c8c8c8; border-radius: 5px; min-width: 466.828px;">
<p class="titulo-campo font1 fw700">Assunto:</p>
<textarea pInputTextarea [rows]="2" [(ngModel)]="disparaEmail.assuntoEmail" style="width: 100%; resize:unset; font-size: 18px;"></textarea>
<p class="titulo-campo font1 fw700">Tipo de Aviso:</p>
<p-editor [style]="{'height':'300px'}" [(ngModel)]="disparaEmail.msgEmail"></p-editor>
<p class="titulo-campo font1 fw700">Data:</p>
<p-calendar [(ngModel)]="disparaEmail.dataEmail" dateFormat="dd/mm/yy" showButtonBar="true" [locale]="br" [monthNavigator]="true"
[yearNavigator]="true" yearRange="2018:2050"></p-calendar>
</div>
</section>
</div>
<div style="display: inline-grid;">
<i class="fa fa-plus botoes-chamada" (click)="addAviso()" style="color: #819049; padding:30px; margin-bottom: 10px;" pTooltip="Adicionar um tipo de aviso."></i>
<i class="fa fa-minus botoes-chamada" (click)="deletaAviso()" style="color: #905149; padding:10px;" pTooltip="Remover o último tipo de aviso inserido."></i>
</div>
这是TS部分:
addAviso(){
this.disparaEmails.push(new EmailDispara());
}
deletaAviso(){
if (this.disparaEmails.length > 1){
this.disparaEmails.splice(this.disparaEmails.length - 1, 1);
}
}
感谢您的提前帮助!
答案 0 :(得分:3)
这可能是未正确检测更改的常见问题。将ChangeDetectorRef注入添加到您的组件中:
constructor (..., changeDetector: ChangeDetectorRef)
并在添加/删除后调用detectChanges
:
addAviso(){
this.disparaEmails.push(new EmailDispara());
this.changeDetector.detectChanges(); // <- this line here
}