我想要一个组件将输入发送到另一个组件。下面是代码.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);
}
}
您需要进行一些更改,因为查看您当前拥有的代码似乎不完整。
this.router
而不在构造函数中注入Router class。this.route
而不在构造函数中注入ActivatedRoute class。<app-child [sostegno]="'Test'"></app-child>
这应该适用于您的子组件内部的ngOnInit
函数。如果这有效,您现在需要做的就是在父组件中初始化sostegno
,否则当您在父类中调用avvia1
或avvia2
时,子组件中的控制台日志将不会反映更改。
希望这可以帮助!