Angular 角度:多个组件中的相同id属性
我刚刚发现,如果我们对多个组件中的HTML元素使用相同的Angular 角度:多个组件中的相同id属性,angular,Angular,我刚刚发现,如果我们对多个组件中的HTML元素使用相同的id属性,并且如果这些组件在视图中一起呈现,那么id将在DOM中重复 例如,考虑下面的场景: //hello.component.html <p id="greet">Hello</p> //welcome.component.html <p id="greet">welcome</p> //app.component.html <app-hello></app-hel
id
属性,并且如果这些组件在视图中一起呈现,那么id
将在DOM
中重复
例如,考虑下面的场景:
//hello.component.html
<p id="greet">Hello</p>
//welcome.component.html
<p id="greet">welcome</p>
//app.component.html
<app-hello></app-hello>
<app-welcome></app-welcome>
//hello.component.html
你好
//欢迎使用.component.html
欢迎光临
//app.component.html
考虑到app hello
,app welcome
分别作为hello
和welcome
组件的选择器,当它们在app
组件中呈现时,它们内部的id
属性将得到重复,并且具有相同的值。因此,这将打破id
的W3C
标准,该标准规定id
属性值在整个DOM
中应该是唯一的
由于组件被称为独立的、封装的UI,我认为在实现组件时,不需要验证所有组件中元素的id
属性是否唯一
那么,在这种情况下,应该采用什么方法来维护唯一的
id
属性呢?这些片段基于Angular,但我认为这个问题适用于所有基于组件的框架,如React、Vue、,等等。在我们的应用程序中,我们不为元素设置Id属性,以防我们想要设置主题,我们使用css类,如果我们想要获取元素的引用,我们使用模板引用来获取该元素,或者使用其他角度的方式从模板中查询元素
你好
组成部分
@ViewChild('greet',{static:true})greetElementRef;
恩戈尼尼特(){
console.log(this.greetemnt.nativeElement)
}
不要在可重用组件中使用id。由这些组件的使用者为组件实例分配(或不分配)id
如果需要关联css,请使用类而不是id
例如:
//hello.component.html
<p class="hello_greet">Hello</p>
//welcome.component.html
<p class="welcome_greet">welcome</p>
//app.component.html
<app-hello id="hello"></app-hello>
<app-welcome id="welcome"></app-welcome>
//hello.component.html
你好
//欢迎使用.component.html
欢迎
//app.component.html
不必要时不要使用ID,或者使用动态生成的ID,或者采用防止冲突的命名约定,或者只是要小心,或者不在乎,因为浏览器不会因为重复的Id而崩溃。@jbnize说我们不再需要使用Id是正确的,因为我们可以使用angular查询任何元素,而只查询用于样式设置的类?在大多数情况下,是的。ID仍然是将标签与表单输入(或选择或文本区域)相关联所必需的。它们对自动化测试非常有帮助。