我試圖在點擊時獲取動態創建的輸入的值
這是代碼:
Save(form:NgForm){
const element = document.createElement("input");
element.setAttribute("type", "text")
element.setAttribute("placeholder", "Title")
element.setAttribute("name", "Title")
element.setAttribute("[(ngModel)]", "Title")
element.setAttribute("class","appearance-none block w-full bg-white text-gray-700 border border-gray-400 shadow-inner rounded-md py-3 px-4 leading-tight focus:outline-none focus:border-gray-500");
document.getElementById("title").appendChild(element)
}
我試過這個 setAttribute 但它沒有用
element.setAttribute("[(ngModel)]", "Title")
它說:無法在“元素”上執行“setAttribute”:“[(ngModel)]”不是有效的屬性名稱。
uj5u.com熱心網友回復:
我不確定我是否理解您嘗試這樣做的原因。但是,如果您不希望使用任何角容量,這意味著您沒有使用任何html帶有精心創建的<input>標簽的檔案,并且通過變數系結了變數 through [(ngModel)],那么您不應[(ngModel)]像您那樣分配。
這意味著以下不起作用,因為它不是來自 htmlinput標記的已知屬性。
element.setAttribute("[(ngModel)]", "Title")
因此,您應該像這樣設定值
element.value = "Title";
小貼士
在這里,如果不需要,您嘗試以 Angular 方式存檔的內容
,請發表評論,我會將其從我的答案中洗掉
<!-- app.component.html -->
<input [(ngModel)]="title" type="text" placeholder="Title" name="Title" class="appearance-none block w-full bg-white text-gray-700 border border-gray-400 shadow-inner rounded-md py-3 px-4 leading-tight focus:outline-none focus:border-gray-500">
// app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class YourComponent {
title: string
save() {
console.log(this.title)
}
}
uj5u.com熱心網友回復:
Angular 不能以這種方式作業,您可以創建一個變數(或一組變數)并在 .html 中使用來創建輸入。例如
//in .ts define an object
inputConfig={type:"text",
placeholder:"Title",
name:"Title",
variable:"title",
class="appearance-none ..."
};
//in .html
<input [type]="inputConfig.type" [placeholder]="inputConfig.placeholder"
[name]="inputConfig.name" [ngClass]="inputConfig.class"
[(ngModel)]="this[inputConfig.variable]">
看看你在 [(ngModel)] 中是如何使用的 this[inputConfig.variable]
一個傻瓜stackblitz
要獲得變數“title”,它只能在 .tsthis.title或 .html 中使用title
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335915.html
上一篇:將物件的變化通知給父角度
下一篇:使用.htaccess轉發路徑
