首页 > 解决方案 > 在子组件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;
    }
  }

}

我已经尝试过的:

  1. 使用 router 属性作为字符串,然后使用该语法:<h1><app-task-title taskId={{router}}></app-task-title></h1>但结果是相同的。
  2. 使用在 DOM 中返回值的方法。

如果您对属性在 DOM 中的行为有任何解释,欢迎

标签: angulartypescriptangular-lifecycle-hooks

解决方案


我的猜测是ngOnInit在子组件中调用得太快并且taskId尚未被重视。如果你想确定,你可以使用@Inputon 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;
      [...]
  }

推荐阅读