4

I have following custom component

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

How Can I get the property name from class in this case "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);
    }

}

angular somehow knows which property it should update. I want to get the reference or name of this property. thanks

Michael
  • 94
  • 7
  • maybe it's hidden in metadata attributes? who knows... – Michael Aug 02 '18 at 18:45
  • 1
    This is a great question, and I'm looking to do the same thing, This would let me auto apply the prop name as an input name value which would simplify more generic components. If I come across an answer I'll update! – Jessy Jan 11 '19 at 15:02
  • thanks @Jessycormier I'll be very thankfull if you do that <3 – Michael Jan 12 '19 at 20:46
  • so far the solution I've gone with is similar to the suggested answer create an `@Input() name;` on my component ( and in my case I put it in my `ElementBase` since I'm extending a base class for common parts of my components). I'm not sure there is a way to get the property name manually since you bind on the property value not the object so there is no prototype or reverse lookup ability here. If I do come across something in my angular adventures I'll be sure to pass along the info! Good luck in yours. – Jessy Jan 15 '19 at 19:45
  • Thanks @Jessycormier. I think maybe the name is hidden in somewhere reflection meta data, since angular uses reflect-metadata library heavily, maybe it also stores it somewhere, who knows.... Anyway, this is very hard to find and/or debug. – Michael Jan 16 '19 at 20:14

1 Answers1

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);
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
  • 1
    Thanks, but I want to avoid this. :) angular know which propety to update, so I want to get this data too – Michael Aug 02 '18 at 12:31