Angular >=6 模板中元素的扩展属性 [英] Spread attributes for an element in Angular >=6 template

查看:25
本文介绍了Angular >=6 模板中元素的扩展属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有这个...

@Component({选择器:'通用输入',模板:`<div><input [formControl]="control"/></div>`,})导出类 GenericInputComponent 实现 OnInit {@Input('config') config = {placeholder: 'Testability', disabled: true, type: 'text'};控制;构造函数(){}ngOnInit() {this.control = new FormControl();}}

我想通过使用某种循环或其他方式来传播配置对象中的属性,以便呈现的 html如下:

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

 <div><input [placeholder]='config.placeholder', [disabled]='config.disabled' [formControl]="control"/></div>

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

解决方案

1.添加模板变量:

<div><input #v [formControl]="control"/></div>

2.在ts中绑定ViewChild:

@ViewChild('v')v:元素引用

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

const el = this.v.nativeElementObject.keys(this.config).forEach(key => el[key] = this.config[key])

更新

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

@Component({选择器:'我的应用',模板:`<div><input #v></div>`})导出类 AppComponent {@ViewChild('v')v:元素引用;config = { placeholder: 'Testability', disabled: true, type: 'text' };ngOnInit() {const el = this.v.nativeElement;Object.keys(this.config).forEach(key => el[key] = this.config[key]);}}

I have this in my code...

@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();
  }

}

I would like to spread the attributes in the config object by using some sort of a loop or something else so that the rendered html is as follows:

<div><input placeholder='Testability', disabled=true type='text' [formControl]="control"/></div>

Note: This following is not an option:

   <div><input [placeholder]='config.placeholder', [disabled]='config.disabled' [formControl]="control"/></div>

Any help and ideas are welcome. Thank you.

解决方案

1.Add a template variable:

<div><input #v [formControl]="control"/></div>

2.Bind ViewChild in ts:

@ViewChild('v')
v: ElementRef

3.Fill values in its nativeElement property:

const el = this.v.nativeElement
Object.keys(this.config).forEach(key => el[key] = this.config[key])

Update

Complete component.ts file would look like this:

@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]);
  }
}

这篇关于Angular &gt;=6 模板中元素的扩展属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆