我有一個基本的 Angular 應用程式,如下所示:
app.component.html:
<head>
<title> My Home Page </title>
</head>
<body>
<h1>Test Umgebung</h1>
<div>
<label>Firstname</label>
<input placeholder="Firstname"/>
</div>
<div>
<label>Lastname</label>
<input placeholder="Lastname"/>
</div>
<div id="cloneContainer">
</div>
<button (click)="cloneUpper()"> Add more Users</button>
</body>
</html>
如您所見,我輸入了用戶,當我單擊“添加更多用戶”按鈕時,應執行以下方法:
app.component.ts:
import { Component } from '@angular/core';
import { CloneComponentComponent } from './clone-component/clone-component.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'UserManager';
cloneUpper(){
console.log("Cloned!");
var cln = new CloneComponentComponent();
var container = document.getElementById('cloneContainer');
container?.append(cln.toString());
}
}
克隆組件只包含名字和姓氏的輸入,以便添加更多用戶。現在,當我單擊按鈕時,它只是將 [object Object] 附加到“cloneContainer”。可能是什么錯誤?
uj5u.com熱心網友回復:
先建議關系,比如父子關系,通過viewChild獲取子組件的方式,或者通過service獲取公共引數
uj5u.com熱心網友回復:
在 Angular 中,您不需要通過getElementById任何方式從 DOM 中獲取。只需添加條件渲染:
<div id="cloneContainer">
<!-- CloneComponentComponent selector -->
<clone-component *ngIf="showClone"></clone-component>
</div>
現在,您的克隆僅在 時可見showClone = true,因此讓我們將此變數添加到您的AppComponent和更改cloneUpper方法中:
export class AppComponent {
title = 'UserManager';
showClone = false;
cloneUpper(){
this.showClone = true;
}
}
如果您需要處理 clild 組件陣列(推送新組件),您可以對陣列執行相同的操作:
<div id="cloneContainer">
<!-- CloneComponentComponent selector -->
<clone-component *ngFor="let clone of clones"></clone-component>
</div>
export class AppComponent {
title = 'UserManager';
clones = [];
cloneUpper(){
this.clones.push(true); // whatever you want
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357532.html
標籤:javascript html 有角的 打字稿
