Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在子组件中插入从url获取的值_Angular_Typescript_Angular Lifecycle Hooks - Fatal编程技术网

Angular 在子组件中插入从url获取的值

Angular 在子组件中插入从url获取的值,angular,typescript,angular-lifecycle-hooks,Angular,Typescript,Angular Lifecycle Hooks,我正在尝试从Url中注入一个值,该Url是我想要注入到子组件中的。 我可以从url获取参数,并使用属性更新DOM,但当我将同一属性注入子组件时,它的行为方式不同 这里是我的父组件: @Component({ selector: 'app-posts', templateUrl: ` <div class="container"> <h1><app-task-title [taskId]="router">&

我正在尝试从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 {
  }
}
@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属性用作字符串,然后使用以下语法:
    ,但结果相同
  • 使用在DOM中返回值的方法

  • 如果您对DOM中属性的行为有任何解释,那就很好了

    我的猜测是
    ngOnInit
    在子组件中调用得太快,而
    taskId
    尚未赋值。如果您想确定,可以在setter上使用
    @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;
          [...]
      }
    

    谢谢你,你的回答对我帮助很大。我需要更多地了解生命周期挂钩,但文档并没有提供很好的示例来理解它