如何获取[(ngModel)]绑定到的属性的名称?角度6

时间:2018-08-02 11:33:03

标签: angular reflection reflect-metadata

我有以下自定义组件

<form-text
    [(ngModel)]="dataItem.prop1">
  </form-text>

在这种情况下,如何从类中获取属性名称“ prop1”?

  @Component({
  selector: 'form-text',
  template: `
    <div>
      <label *ngIf="label" [attr.for]="identifier">{{label}}</label>
      <input
        type="text"
        [(ngModel)]="value"
      />
    </div>
  `,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: FormTextComponent,
    multi: true,
   }],
  })
export class FormTextComponent extends ElementBase<string>{

    @ViewChild(NgModel) model: NgModel;

    constructor(@Optional() @Inject(NG_VALIDATORS) validators: Array<any>){
       super(validators);
    }

}

角以某种方式知道应该更新哪个属性。 我想获取此属性的引用或名称。 谢谢

1 个答案:

答案 0 :(得分:0)

You can pass an @input property 'propname' with value as string.

<form-text
    required
    hexadecimal
    [dataV]="data"
    placeholder="Enter a hexadecimal value"
    label="Value 1"
    #prop1=ngModel
    [(ngModel)]="dataItem.prop1"
    propname="'prop1'"
    >
  </form-text>

In FormTextComponent,

@input() propname: string;
@ViewChild('prop1') propmodel: ngModel;

console.log(this.propname); // prop1
console.log(this.propmodel);