首页 文章

如何在Angular 5中设置孩子(或第n个孩子)组件的子项的属性

提问于
浏览
2

如何在不创建中间变量的情况下从Angular 5中的父项设置子项(或n级子组件)的子项的属性 . 例如,假设我有一个子组件,如下所示 .

@Component({
  selector: 'app-child11',
  template: '<p>
child11 works!
Name is {{name}}</p>', styleUrls: ['./child11.component.css'] }) export class Child11Component implements OnInit { @Input() name: string; constructor() {} ngOnInit() {} }

让我们说我的child11的父亲是child1,如下所示

@Component({
  selector: 'app-child1',
  template: '<p>child1 works!<app-child11 name="Karthik"></app-child11></p>',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
  constructor() {}

  ngOnInit() {}
}

并且父组件如下所示

@Component({
  selector: 'app-root',
  template: '<div><app-child1></app-child1></div>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

现在我如何修改app-root的模板,以便我可以直接在app-root中设置child11的名称值,而不在Child1中引入传播到AppComponent的变量?

2 回答

  • -1

    如果我想这样做,我宁愿使用绑定组件输入而不是简单输入 .

    我准备的代码是 .

    app.component.ts

    import { OnInit, Component, Input } from "@angular/core";
    
    @Component({
      selector: 'app-child11',
      template: '<p>
    child11 works!
    Name is {{name}}</p>', styleUrls: [] }) export class Child11Component implements OnInit { @Input() name: string; constructor() { } ngOnInit() { } } @Component({ selector: 'app-child1', template: '<p>child1 works!<app-child11 [name]="name"></app-child11></p>', styleUrls: [] }) export class Child1Component implements OnInit { constructor() { } @Input() name: string; ngOnInit() { } } @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; name: string; }

    app.component.html

    <p>child1 works!
        <app-child11 [name]="name"></app-child11>
    </p>
    <br>
    <input type="text" [(ngModel)]="name"/>
    

    现在无论你在app-root组件中的输入标签内写什么都将到达app-child11,最后它将在那里打印 .

    我希望它可以帮到你 .

  • -2

    如果您不想创建中间变量,可以创建 Service ,例如 ChildService . Service Guide . 创建 child$: Observable<any[]>child$$: Subject<any[]> 并订阅 Child11Component

    this.child$
        .filter(child => child.name === this.name)
        .subscribe(child => this.child = child);
    

    你的 this.child 变量有必要的孩子 .

相关问题