Access a DOM element in Angular 2 and change an element's class attribute

I am new to angular2. my code looks like this:

import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'main',
   template: `
    <div class="current">
    </div>
  `
})

export class MainComponent implements OnInit {
   ngOnInit(): void {
     //change the div class from current to next...
   }
}

I would like to change the div class from 'current' to 'next'.

i fit if you let me know what is the best way to do this?

+4
source share
1 answer

One option is to use a template reference variable .

In the example below, the reference variable is #targetadded to the desired element, and then decorator@ViewChild ( @ViewChild('target') target) allows you to access the variable in your component.

DOM, nativeElement .

, :

import { Component, AfterViewInit, ViewChild } from '@angular/core';

@Component({
  selector: 'main',
  template: `
  <div #target class="current">
  </div>
  `
})
export class MainComponent implements AfterViewInit {
  @ViewChild('target') target;

  constructor() { }

  ngAfterViewInit(): void {
    let element = this.target.nativeElement;

    element.className = 'next';
  }
}

, DOM DOM-. ngClass class:

import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'main',
  template: `
  <div [ngClass]="targetClass">
  </div>
  `
})
export class MainComponent implements AfterViewInit {
  private targetClass: string = 'current';

  constructor() { }

  ngAfterViewInit(): void {
    this.targetClass = 'next';
  }
}
+5

Source: https://habr.com/ru/post/1670484/


All Articles