0

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');
  }
  }
}
4
  • you need to add the html side of this component in the question Commented Nov 12, 2017 at 10:59
  • That will be the part of the answer. Please check the plunkr Commented Nov 12, 2017 at 11:02
  • you need to provide a minimal reproducible example here and not in a link Commented Nov 12, 2017 at 11:04
  • Thats the working plunkr with minimal code Commented Nov 12, 2017 at 11:05

1 Answer 1

1

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');
}
Sign up to request clarification or add additional context in comments.

4 Comments

sorry thats incorrect. check this plnkr plnkr.co/edit/5Htzsl0jp4ZdKeqrkAlU?p=preview The p tag doesnt work by that way
I realized the problem, This was because vc was only referring to first instance of ViewChild() defined in the component. Check my edited answer. :)
I wanted to pass without a reference.
I just checked the first example is working correctly. It was not working in the plunkr because you had the wrong order actually. In your example you declared view child before directive declaration on the DOM. If you write <h1 changeStyleClass #h1Ref>change this to green color</h1> instead of <h1 #h1Ref changeStyleClass>change this to green color</h1> It won't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.