Reputation: 1399
I pass a dom node along with a classname to a directive where the directive then will add class to the passed dom element. I get an error Cannot read property addclass of undefined. Please have a look at the plnkr. https://plnkr.co/edit/kT37XoeMWMZ7qexwZ15W?p=preview
export class App implements AfterViewInit {
constructor(private el: ElementRef) {
}
@ViewChild(changeStyleClass) vc: changeStyleClass;
@ViewChild('h1Ref') h1: el;
@ViewChild('mbc') mbc: el;
ngAfterViewInit() {
this.vc.addClass(this.h1.nativeElement, 'redColor');
this.vc.addClass(this.mbc.nativeElement, 'makeBorder');
}
}
}
Upvotes: 0
Views: 3720
Reputation: 321
Apply your directive to DOM elements.
<h1 changeStyleClass #h1Ref>change this to green color</h1>
<p changeStyleClass #mbc>make border class</p>
Edit
Instead of creating a ViewChild reference for a directive. You can also use nativeElement.classList to add and remove classes on the element directly too.
@ViewChild('h1Ref') h1: ElementRef;
@ViewChild('mbc') mbc: ElementRef;
ngAfterViewInit() {
this.h1.nativeElement.classList.add('makeBorder');
this.h1.nativeElement.classList.add('redColor');
this.mbc.nativeElement.classList.add('makeBorder');
this.mbc.nativeElement.classList.add('redColor');
}
Upvotes: 1