在{{}}(花括号)内使用函数调用是一种好的做法吗?
有没有办法在组件内完成这个操作,例如(也许使用 ngOnChanges
或其他什么...)
模板
<div class="container">
{{ bootstrap() }}
{{ validate() }}
<textarea class="form-control">{{ fullHtml }}</textarea>
<button (click)="copy()" class="btn btn-primary">Click to Copy HTML</button>
<textarea class="form-control">{{ validator }}</textarea>
<button (click)="copy()" class="btn btn-warning">Click to Copy Validate</button>
<button class="btn btn-danger" (click)="add()">Add page and input</button>
</div>
组件
class HomeComponent {
fullHtml = "";
validator = "";
pages = [{
"name": "Page 1"
},{
"name": "Page 2"
}];
inputs = [{
"name": "input_1",
"required": true
},{
"name": "input_2",
"required": false
}];
public bootstrap() {
this.fullHtml = this.pages.map((page, pageNumber) => {
return '<div class="row">' +
page.name +
'</div>'
}).join('')
}
public validate(){
this.validator = this.inputs.map((input, i) => {
return '"' + input.name + '" => [' + (input.required? 'required': 'nullable') + '],\n';
}).join('')
}
public copy(){
alert("under construction");
}
public add(){
this.pages.push({
name: "page 3"
});
this.inputs.push({
"name": "input_3",
"required": true
});
}
}
https://jsfiddle.net/1hk7knwq/10283/
ps. 我需要在文本区域中显示HTML内容,因此我正在组件内部进行HTML编写。