我想要一个组件将输入发送到另一个组件。下面是代码 .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);
}
}
最佳答案
您需要进行一些更改,因为查看您当前拥有的代码似乎不完整。
您正在使用
this.router
而没有注入(inject) Router class在你的构造函数中。您正在使用
this.route
而没有注入(inject) ActivatedRoute class在你的构造函数中。要测试您的 parent > child 互动是否有效,您可以删除您的参数,而是对 html 进行测试
<app-child [sostegno]="'Test'"></app-child>
这应该适用于您的子组件内的 ngOnInit
函数。如果这有效,您现在需要做的就是在您的父组件中初始化 sostegno
否则您的子组件中的控制台日志将不会在您调用 avvia1
或 avvia2
在你的父类中。
希望这对您有所帮助!
关于html - 组件交互@Input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54986202/