首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角>=6模板中元素的扩展属性

角>=6模板中元素的扩展属性
EN

Stack Overflow用户
提问于 2018-12-19 05:18:22
回答 1查看 1.5K关注 0票数 2

我的密码里有这个。

代码语言:javascript
复制
@Component({
  selector: 'generic-input',
  template: `<div><input [formControl]="control"/></div>`,
})
export class GenericInputComponent implements OnInit {

  @Input('config') config = {placeholder: 'Testability', disabled: true, type: 'text'};

  control;

  constructor() { }

  ngOnInit() {
    this.control = new FormControl();
  }

}

我希望通过使用某种循环或其他方法扩展config对象中的属性,以便呈现的html如下所示:

代码语言:javascript
复制
<div><input placeholder='Testability', disabled=true type='text' [formControl]="control"/></div>

备注:以下不是一个选项:

代码语言:javascript
复制
   <div><input [placeholder]='config.placeholder', [disabled]='config.disabled' [formControl]="control"/></div>

欢迎任何帮助和想法。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-19 05:38:01

1.添加一个模板变量:

代码语言:javascript
复制
<div><input #v [formControl]="control"/></div>

2.在ts中绑定ViewChild

代码语言:javascript
复制
@ViewChild('v')
v: ElementRef

3.在其nativeElement属性中填充值:

代码语言:javascript
复制
const el = this.v.nativeElement
Object.keys(this.config).forEach(key => el[key] = this.config[key])

更新

完整的component.ts文件如下所示:

代码语言:javascript
复制
@Component({
  selector: 'my-app',
  template: `<div><input #v></div>`
})
export class AppComponent {
  @ViewChild('v')
  v: ElementRef;

  config = { placeholder: 'Testability', disabled: true, type: 'text' };

  ngOnInit() {
    const el = this.v.nativeElement;
    Object.keys(this.config).forEach(key => el[key] = this.config[key]);
  }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53845004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档