![](/img/trans.png)
[英]Rendering an Angular Component into the DOM without Component wrapper
[英]Side effects of removing Angular component wrapper tags from DOM
假設我有一個名為<hello-world>
的組件,它具有以下 HTML 模板:
<div>Hello World!</div>
通過使用這個組件並在 DOM 中進行檢查,它呈現如下:
<hello-world>
<div>Hello World!</div>
</hello-world>
我不想要<hello-world>
和</hello-world>
的包裝元素,因此通過編寫幾行 Java 腳本代碼,我將它們從 DOM 中刪除,一切仍然正常。
我知道 Angular 團隊不建議這樣做,但只是想知道這是否會對 Angular 的運行方式產生任何副作用?
對於有興趣查看有關如何刪除包裝器的代碼的人。 它是從 ngOnInit() 調用的。
const self: HTMLElement = this.elementRef.nativeElement
const parent: HTMLElement = self.parentElement
while (self.firstChild)
parent.insertBefore(self.firstChild, self)
parent.removeChild(self)
您可以使用與組件指令相同的選擇器。 我不會推薦它,但它確實有效。
https://stackblitz.com/edit/angular-ivy-f86erf?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fhello.component.ts,src%2Fapp%2Fapp.component.ts在 div 中使用 hello 組件的簡單示例
所以本質上你想要一個帶有[]
的選擇器,它將組件的內容插入其中。
@Component({
selector: 'hello,[hello]',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
@Input() name: string;
}
並使用
<div hello></div>
就個人而言,我唯一一次找到這樣做的正當理由是制作需要特定標簽的 svg 組件。 除此之外,我會避免這樣做。 否則,如果它只是做 dom 操作,那么你應該只使用指令,它們就是為此而生的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.