html - 模板标签内容为空
问题描述
我正在尝试template
在 Angular 组件中使用标签。
在MDN 示例之后,我创建了一个类似的stackblitz 示例。
在原始示例中,template
标签没有子级,但它的内容有子级。在我的例子中,情况正好相反。模板有孩子,内容为空(打开控制台并单击按钮查看)。
结果,尝试操作克隆的模板内容失败。
我究竟做错了什么?
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
click() {
const template: HTMLTemplateElement = document.querySelector('#t');
console.log(`template.childElementCount: ${template.childElementCount}`);
console.log(`template.content.childElementCount: ${template.content.childElementCount}`);
const content = document.importNode(template.content, true);
console.log(content.querySelector('.c2'));
}
}
app.component.html
<button (click)="click()">test</button>
<template id="t">
<div class="c1">
<div class="c2">{{ name }}</div>
</div>
</template>
控制台结果
解决方案
推荐阅读
- typescript - 类型中所有属性名称的数组
- python - 列表项的assertEqual自定义比较
- android - 每当我开始一个新项目时,我都无法在 android studio 中更改我的活动和布局文件名?
- reactjs - 使用 redux saga 阻止 takeEvery
- javascript - 我们可以删除轮播光滑滑块中的固定滚动吗?
- karate - 在空手道测试步骤中使用 if 条件的语法是什么?
- javascript - 错误:参数“value”的值不是有效的查询约束。不能将“未定义”用作 Firestore 值
- r - 如何在保留整个数据框的同时将函数应用于某些列?
- java - 如何实现自定义 SubtitleDecoderFactory 包装 SubtitleDecoderFactory.DEFAULT,这是一个常量实例
- ios - 如何仅显示 SwiftUI 列表中的选定项目?