组件交互@Input

问题描述 投票:2回答:1

我想要一个组件将输入发送到另一个组件。下面是代码.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);
       }

    }
html angular input components interaction
1个回答
1
投票

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

  1. 您正在使用this.router而不在构造函数中注入Router class
  2. 您正在使用this.route而不在构造函数中注入ActivatedRoute class
  3. 要测试您的父>子交互是否正常工作,您可以删除您的参数,而是为html进行测试
<app-child [sostegno]="'Test'"></app-child>

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

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.