Javascript 如何向Angular2+;中动态创建的元素添加属性;?
我已经看过了,但它不起作用——可能是因为我瞄准的元素是在自定义组件中动态生成的(Javascript 如何向Angular2+;中动态创建的元素添加属性;?,javascript,angular,attributes,add,angular-renderer2,Javascript,Angular,Attributes,Add,Angular Renderer2,我已经看过了,但它不起作用——可能是因为我瞄准的元素是在自定义组件中动态生成的() 我也看了一下,但我认为这不起作用,因为我无法触摸自定义组件的代码 相关要素 HTML 我曾尝试在ngOnInit和ngOnViewInit方法中使用上述方法,但没有任何帮助。 奇怪的是,该方法在页面呈现后在Chrome控制台窗口中工作。即querySelected items get id属性 方法2。使用Angular的渲染器2。(无可否认,我不知道如何获得需要id的特定本机元素 //first, decla
)
我也看了一下,但我认为这不起作用,因为我无法触摸自定义组件的代码
相关要素
HTML
我曾尝试在ngOnInit和ngOnViewInit方法中使用上述方法,但没有任何帮助。
奇怪的是,该方法在页面呈现后在Chrome控制台窗口中工作。即querySelected items get id属性
方法2。使用Angular的渲染器2。(无可否认,我不知道如何获得需要id的特定本机元素
//first, declare target custom component element with viewchild:
export class MainComponent implements OnInit, AfterViewChecked, AfterViewInit {
@ViewChild('mainComponentTabs1', { static: true }) c_tabs1: ElementRef;
...
ngAfterViewChecked() {
//neither of these approaches works.
const c_tabs1El = this.c_tabs1.nativeElement;
this.renderer.setAttribute(c_tabs1El.items[0], 'id', 'dashboard-tab-link-search');
const c_tabs1El2 = document.querySelectorAll("button.c-item");
this.renderer.setAttribute(c_tabs1El2[0].nativeElement, 'id', 'dashboard-tab-link-dashboard');
}
...
}
如果您试图通过类或标记来确定元素的目标,我不确定您要针对哪些元素,但我认为以下代码将帮助您: 导出类MainComponent实现OnInit、AfterViewChecked、AfterViewInit{ //只有在ngOnInit中使用static属性时,该属性才必须为true @ViewChild('mainComponentTabs1',{static:false})c_tabs1:ElementRef; ... ngAfterViewInit(){ const targetElements=this.c_tabs1.nativeElement.querySelectorAll('button.c-item')) targetELements.forEach((el,index)=>this.renderer.setAttribute(el,'id','dashboard tab link search-${index}'); } ... }
不要直接接触DOM。这是有效的——但只有当我将此代码放入ngAfterViewChecked()中时才有效生命周期方法!TY!@inonut-t如果我们可以使用document可靠地定位元素,那么是否有充分的理由使用本地引用和ViewChild。querySelector/All?@PakiPat使用
document
被认为是不好的做法,因为在没有可用浏览器的情况下(例如使用Universal进行服务器端渲染).ElementRef和RenderR2为此类情况提供了一个抽象。
ngAfterViewInit() {
let att = document.createAttribute("id");
att.value = "yada1";
document.querySelectorAll(".c-tabs .hydrated")[0].setAttributeNode(att);
}
//first, declare target custom component element with viewchild:
export class MainComponent implements OnInit, AfterViewChecked, AfterViewInit {
@ViewChild('mainComponentTabs1', { static: true }) c_tabs1: ElementRef;
...
ngAfterViewChecked() {
//neither of these approaches works.
const c_tabs1El = this.c_tabs1.nativeElement;
this.renderer.setAttribute(c_tabs1El.items[0], 'id', 'dashboard-tab-link-search');
const c_tabs1El2 = document.querySelectorAll("button.c-item");
this.renderer.setAttribute(c_tabs1El2[0].nativeElement, 'id', 'dashboard-tab-link-dashboard');
}
...
}