2
votes

Using "@angular/core": "^5.0.1", "@angular/material": "^5.0.0-rc.1", "@angular/cdk": "^5.0.0-rc.1".

I have functionality like checking all the fields have a XXXqaName attribute added to it, so added a directive with @input attribute which accepts the XXXqaName

Static input like qa-name="matselectone" for selector mat-select element Works Fine and XXXqaName attribute appeared in HTML template like :

enter image description here

<mat-select XXXqaName="matselectone"></mat-select> // Works fine

When adding dynamic values for mat-options like XXXqaName="data-{{ option.value }}" input is not passes(i.e undefined) and XXXqaName attribute is not found in HTML template like

<mat-option XXXqaName="data-{{ option.value }}"></mat-option> // XXXqaName missing in HTML template only ng-reflect name is present.

enter image description here

Note: option.value is there and option value in dropdown is populated except the attribute "xxxqaName" is missing in HTML.

Directive :

@Directive({
     selector: `input[type="text"], mat-select, mat-option`
 })
export class QaDirective implements OnInit {

   @Input('XXXqaName') qaName: string;

   constructor(private element: ElementRef) { }

   ngOnInit() { this.verifyQa();}

   verifyQa(): void {
   if (!this.qaName) {
   console.error('No "XXXqaName" provided for:',This.element.nativeElement);
   return;
   }
  }
}

Directive when passing dynamic value for input attribute value remains undefined. Is there alternative way to pass dynamic value into directive Any help would be great.

Note : Might look like Dynamic attribute values for directives but they use function in their component to manipulate input. Here it is slightly diff the attribute remains undefined.

1
When inspecting html template couldn't find attribute Of course you won't see those attributes since you're binding to property - yurzui
yes cant bind property great. - Karthigeyan Vellasamy
I added @HostBinding('attr.qa-name') front of @Input('qa-name') - yurzui

1 Answers

2
votes

update

Property bindings are not added to the DOM. If you want a binding to become an attribute, use the attr. binding

attr.XXXqaName="data-{{ option.value }}"

or

[attr.XXXqaName]="'data-' + option.value"

StackBlitz example

original

When you check the attribute it isn't yet created

Use ngAfterViewInit() instead

@Directive({
     selector: `input[type="text"], mat-select, mat-option`
 })
export class QaDirective implements OnInit {

   @Input('XXXqaName') qaName: string;

   constructor(private element: ElementRef) { }

  ngOnChanges() {
    this.verifyQaNameAttr();
  }

   verifyQa(): void {
   if (!this.qaName) {
   console.error('No "XXXqaName" provided for:',This.element.nativeElement);
   return;
   }
  }
}