【发布时间】:2021-03-06 13:16:57
【问题描述】:
我正在尝试在自定义指令中获取组件(标头)的属性 ID。同时我正在使用布局来显示标题。为此,我使用this.renderer.appendChild(this.elementRef.nativeElement, p);,但问题是我需要将此段落添加到特定的div(<div #identifier class="mid"></div>)中。这是我的代码:
HTML 布局
<div class="grid">
<header mId id="navbar"></header>
</div>
标题组件
<div class="header-container">
<h1 id="logo">...</h1>
.
.
.
<div #identifier class="mid"></div>
</div>
指令
import { ContentChild, Directive, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { myService } from 'src/app/myService/service';
@Directive({
selector: '[mId]'
})
export class IdDirective {
@ViewChild('identifier') mId: ElementRef;
constructor(private renderer: Renderer2, private myService: Service, private elementRef: ElementRef) {
this.method();
}
method() {
this.service.getId().subscribe((response) => {
const p = this.renderer.createElement('p');
const text = this.renderer.createText('ID: ' + response.id);
console.log(response.id);
this.renderer.appendChild(p, text);
this.renderer.appendChild(this.elementRef.nativeElement, p);
});
}
}
结果是 id 号被放置在底部布局的 <header> 标记内,例如:
<header mId id="navbar">
<h1 id="logo">...</h1>
.
.
.
<div #identifier class="mid"></div>
.
.
.
<p>ID: 1</p>
</header>
我需要最终的结果是:
<header mId id="navbar">
<h1 id="logo">...</h1>
.
.
.
<div #identifier class="mid">
<p>ID: 1</p>
</div>
</header>
谁能知道我该怎么做或者我做错了什么?
【问题讨论】:
-
您能解释一下IdDirective的用途吗?为什么你把这段代码提取到这样的指令中?它会在其他地方重复使用吗?
-
@VilmantasBaranauskas 是的,这段代码的目的是在未来的新组件中重用它
标签: angular angular6 angular8 angular-directive directive