您好,我有一个简单案例的奇怪行为。我在每次单击按钮时都要检查n个类变量,当它为null时,我将其初始化,以防万一不是,那么我只是打印此值,但仅在两次单击相同按钮并保持两次的情况下才有效据我了解,该变量应为每次点击共享。
html:
@Component({
selector: 'app-categories',
styleUrls: ['./tree-view.css'],
template: `
<ul>
<li>
<button id={{categories.name}} [ngStyle]="hoverFlag ? matchHoverButtonColor(categories) : matchButtonColor(categories)"
(mouseover)="hoverFlag = true" (mouseout)="hoverFlag = false" class="btn btn-radius" type="button"
(click)="markToSwap(categories.name)"> {{categories.name}} </button>
<ng-container *ngIf="categories.nestedCategories">
<app-categories *ngFor="let cat of categories.nestedCategories" [categories]="cat"></app-categories>
</ng-container>
</li>
</ul>
`,
})
export class TreeViewComponent {
@Input() categories: AdminCategory;
fileNameDialogRef: MatDialogRef<ModalCategoryComponent>;
firstTextSwap = null;
constructor(private dialog: MatDialog, private categoryStylesService: CategoryStylesService) { }
matchButtonColor(category: AdminCategory) { return this.categoryStylesService.matchButtonColor(category); }
matchHoverButtonColor(category: AdminCategory) { return this.categoryStylesService.matchHoverButtonColor(category); }
markToSwap(categoryName: string) {
if (this.firstTextSwap === null) {
console.log(this.firstTextSwap);
this.firstTextSwap = document.getElementById(categoryName).textContent.trim();
console.log(this.firstTextSwap);
}
}
}
点击2次即可获得控制台输出,每次点击均在不同的按钮上:
null
asdadadadadad
null
rrrrrrr
为什么第二次点击时firstTextSwap
为空? html和打字稿代码在同一文件中,我不会重新加载任何内容,省略的代码也不会影响firstTextSwap
答案 0 :(得分:0)
发生这种情况的原因是因为您的模板正在app-categories
循环内创建“ TreeViewComponent”(它似乎具有*ngFor
的选择器),该循环将为该组件创建新的实例。每个项目,列表中的每个项目都有自己的变量集,在每个实例上设置为null
。我认为这不是您想要的,我很惊讶它没有抛出更多错误,因为它看起来像一个递归模板,因为它本身就在调用。
希望这能解释您的错误-我可以更详细地重写您的示例,但是希望这有道理。尽管有一些技巧,*ngFor=
应该位于您的<li>
元素上,并且除非出于某些原因我不知道,否则组件不应从内部调用其模板。