Angular 17+ 高级教程 – Component 组件 の Query Elements

发布时间 2023-12-26 14:58:30作者: 兴杰

前言

Angular 是 MVVM 框架。

MVVM 的宗旨是 "不要直接操作 DOM"。

在 Component 组件 の Template Binding Syntax 文章中,我们列举了一些常见的 DOM Manipulation。

const element = document.querySelector<HTMLElement>('.selector')!;
element.textContent = 'value'; // update text
element.title = 'title'; // update property
element.setAttribute('data-value', 'value'); // set attribute (note: attribute and property are not the same thing)
element.style.padding = '16px'; // change style
element.classList.add('new-class'); // add class

const headline = document.createElement('h1');
headline.textContent = 'Hello World';
element.appendChild(headline); // append a element
element.innerHTML = `<h1>Hello World</h1>`; // write raw HTML

element.addEventListener('click', () => console.log('clicked')); // listen and handle a event

Template Binding Syntax 解决了上面许多的场景,但任然有一些 DOM Manipulation 是无法通过 Template Binding Syntax 解决的。

比如说

  1. document.querySelector
    query descendant
  2. document.body.closest
    query ancestor
  3. slot.assignedElements
    query content projection (a.k.a slot)

 

 

 

这篇,我们继续