组件交互@Input

时间:2019-03-04 15:19:22

标签: html angular input components interaction

我希望一个组件将输入发送到另一个组件。下面是代码.ts和.html。这两个组成部分中的一个 现在的问题是父组件的html页面还显示了子组件的html部分……我希望该组件仅将一个字符串传递给子组件

Parent.ts

import ...

@Component({
  selector: 'app-parent',
  templateUrl: './parent.html',
  styleUrls: ['./parent.css']
})
export class ParentComponent implements OnInit {

  sostegno : string;

  constructor() { }

  ngOnInit() { }

  avvia1() {
    this.sostegno = "xxx";
    this.router.navigate(['./xxx'], { relativeTo: this.route });
  }

  avvia2()
    this.sostegno = "yyy";
    this.router.navigate(['./yyy'], { relativeTo: this.route });
  }
}

Parent.html

<div>
  ...
</div>
<app-child [sostegno]="sostegno"></app-child>

Child.ts

import ...

    @Component({
      selector: 'app-child',
      templateUrl: './child.html',
      styleUrls: ['./child.css']
    })
    export class ChildComponent implements OnInit {

      @Input() sostegno : string;

      constructor() { }

      ngOnInit() {
        console.log(this.sostegno);
       }

    }

1 个答案:

答案 0 :(得分:1)

您需要进行一些更改,因为查看您当前拥有的代码似乎不完整。

  1. 您正在使用this.router,而没有在构造函数中注入Router class

  2. 您正在使用this.route,而没有在构造函数中注入ActivatedRoute class

  3. 要测试您的父代>子代互动是否正常,您可以删除参数,然后对html进行测试

<app-child [sostegno]="'Test'"></app-child>

这应该适用于您的子组件内部的ngOnInit函数。如果此方法奏效,那么您现在要做的就是在父组件中初始化sostegno,否则在子组件中调用avvia1avvia2时子组件中的控制台日志将不反映更改。你的父母班。

希望这会有所帮助!

相关问题