我正在尝试从我想在子组件中注入的Url中注入一个值。我可以从url中获取参数,并使用一个属性更新DOM,但是当我将其注入子组件中时,相同的属性的行为并不相同。
这是我的父组件:
@Component({
selector: 'app-posts',
templateUrl:
`
<div class="container">
<h1><app-task-title [taskId]="router"></app-task-title></h1>
<h2>{{router}}</h2>
<app-tab [tacheLabelId]="router"></app-tab>
</div>
`,
styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit, DoCheck {
/**Variables from the url */
router! : number
constructor(private route : ActivatedRoute) { }
ngDoCheck(): void {
this.router = Number(this.route.snapshot.paramMap.get('route'));
}
ngOnInit(): void {
}
}
我可以看到h2标签发生了变化,但其他的却没有
这是我的孩子部分:
@Component({
selector: 'app-task-title',
template: `
{{taskLabel}}
`,
styles: [
]
})
export class TaskTitleComponent implements OnInit {
@Input() taskId! : number;
taskLabel!: string;
constructor() { }
ngOnInit(): void {
switch (this.taskId) {
case 1:
this.taskLabel = "Title 1"
break;
case 2:
this.taskLabel = "Title 2"
break;
case 3:
this.taskLabel = "Title 3"
break;
case 4:
this.taskLabel = "Title 4"
break;
default:
this.taskLabel = "Title 0"
break;
}
}
}
我已经尝试过的
<h1><app-task-title taskId={{router}}></app-task-title></h1>
但是结果是相同的。如果您对DOM中属性的行为有任何解释,欢迎使用
我的猜测是ngOnInit
在子组件中调用该函数为时过早,taskId
尚未得到重视。如果您想确定的话,可以@Input
在设置器上使用:
export class TaskTitleComponent {
// You might not need this attribute anymore
private _taskId! : number;
taskLabel!: string;
@Input()
set taskId(taskId: number) {
this._taskId = taskId;
switch (this._taskId) {
case 1:
this.taskLabel = "Title 1"
break;
[...]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句