angular - 在子组件Angular中注入从url获取的值
问题描述
我正在尝试从要注入子组件的 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;
}
}
}
我已经尝试过的:
- 使用 router 属性作为字符串,然后使用该语法:
<h1><app-task-title taskId={{router}}></app-task-title></h1>
但结果是相同的。 - 使用在 DOM 中返回值的方法。
如果您对属性在 DOM 中的行为有任何解释,欢迎
解决方案
我的猜测是ngOnInit
在子组件中调用得太快并且taskId
尚未被重视。如果你想确定,你可以使用@Input
on a setter 代替:
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;
[...]
}
推荐阅读
- javascript - 如何在 sequelizejs 的 where 属性中检查我的哪些条件为真
- java - Grails 3.3.9 - 期待“界面”,发现'
' - angular - TS2684 与 Angular 中的 HttpClient 响应
- google-bigquery - 无法使用服务帐号创建 Big Query Data Transfer 作业
- angular - 测试 REST API 调用序列 - “没有当前规范”
- angular - 在 SCSS/SASS/Angular 7 中获取当前页面的背景颜色
- php - 将 Eloquent 枢轴值传递给 Laravel API 资源
- typescript - 如何在打字稿的笑话中调用 VueJS 方法?
- android - 推送通知点击打开最新文章,不是相关文章
- symfony - symfony 联系表格已提交,但电子邮件未到达