📜  angular 7 selected - Javascript (1)

📅  最后修改于: 2023-12-03 14:39:12.473000             🧑  作者: Mango

Angular 7 Selected - JavaScript

Angular 7 is a popular JavaScript framework for building dynamic web applications. One of its many features is the ability to select elements on a web page and perform actions on them.

Selecting Elements

There are several ways to select elements in Angular 7 using JavaScript. One popular method is using the ViewChild decorator. This decorator allows you to select a specific element on a web page and assign it to a variable in your component.

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

@Component({
  selector: 'app-root',
  template: '<div #myDiv>Hello World</div>'
})
export class AppComponent {
  @ViewChild('myDiv') myDiv: ElementRef;

  ngAfterViewInit() {
    console.log(this.myDiv.nativeElement.innerHTML); // Output: Hello World
  }
}

In the above example, we are selecting the div element with the #myDiv attribute using the ViewChild decorator. We are then accessing the innerHTML property of the element in the ngAfterViewInit lifecycle hook.

Performing Actions

Once you have selected an element, you can perform actions on it using JavaScript. One common action is changing the text or HTML content of an element.

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

@Component({
  selector: 'app-root',
  template: '<div #myDiv>Hello World</div>'
})
export class AppComponent {
  @ViewChild('myDiv') myDiv: ElementRef;

  ngAfterViewInit() {
    this.myDiv.nativeElement.innerHTML = 'Goodbye World';
  }
}

In the above example, we are using the innerHTML property to change the content of the div element to 'Goodbye World'.

Conclusion

Angular 7 provides a powerful toolset for selecting and manipulating elements on a web page using JavaScript. With the ViewChild decorator and other features, you can create powerful and dynamic web applications with ease.