【问题标题】:Component Interaction @Input组件交互@Input
【发布时间】:2019-07-25 22:33:58
【问题描述】:

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

父母.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 });
  }
}

父.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);
       }

    }

【问题讨论】:

    标签: html angular input components interaction


    【解决方案1】:

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

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

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

    3. 要测试您的父 > 子交互是否正常,您可以删除您的参数并改为对 html 进行测试

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

    这应该适用于您的子组件内部的ngOnInit 函数。如果这可行,您现在需要做的就是在父组件中初始化sostegno,否则当您在父类中调用avvia1avvia2 时,子组件中的控制台日志将不会反映更改。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 2017-08-26
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2020-06-01
      相关资源
      最近更新 更多