如何通过在父视图中单击事件来访问子组件中的函数。
我的父视图中有两个按钮,每个按钮代表一个组件。
<ul>
<li><button (click)="buttonOne()">component 1</button></li>
<li><button (click)="buttonTwo()">component 2</button></li>
</ul>
&#13;
我想点击按钮组件1并显示组件1,当我点击按钮组件2时,隐藏组件1并显示组件2.
child.component
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'component1',
templateUrl: './componentOne.component.html',
styleUrls: ['./componentOne.component.less']
})
export class ComponentOne implements OnInit {
showComponent: boolean = false;
constructor() {}
buttonOne(): boolean {
this.showComponent = true;
}
buttonTwo(): boolean {
this.showComponent = false;
}
ngOnInit() {}
}
&#13;
parent.component
import { Component, OnInit } from '@angular/core';
import { ComponentOne } from '...parent-component/component-one.component';
@Component({
selector: 'parent-component',
templateUrl: 'parent-component.component.html',
styleUrls: ['parent-component.component.less']
})
export class ParentComponent implements OnInit {
constructor() {}
ngOnInit() {
}
ngOnDestroy() {
}
}
&#13;
答案 0 :(得分:1)
我不知道你是如何创建组件的,但我是如何学习组件的
<ul>
<li><component1>component 1</component1></li>
<li><component2>component 2</component2></li>
</ul>
鉴于此,您应该将局部变量添加到组件HTML中,如下所示:
<ul>
<li><component1 #comp1>component 1</component1></li>
<li><component2 #comp2>component 2</component2></li>
</ul>
通过这样做,您允许Angular获得子引用,您可以使用
进入TS@ViewChild(Component1Component): comp1: Component1Component;
@ViewChild(Component2Component): comp2: Component2Component;
然后,允许你做
this.comp1.myFunctionToCall();
this.comp2.myFunctionToCall();
或者,在您的HTML中,您可以像这样使用局部变量
<ul>
<li><component1 #comp1 (click)="comp1.myFunctionToCall()">component 1</component1></li>
<li><component2 #comp2 (click)="comp2.myFunctionToCall()">component 2</component2></li>
</ul>
答案 1 :(得分:1)
显示子组件的代码应该在父组件中,它可以是这样的:
父组件:
declare @mystring varchar(100)
select @mystring = '0.025000'
-- here's a breakdown of each step in the process ...
select ':'+ @mystring + ':' union all
select ':'+ str_replace(@mystring,'0',' ') + ':' union all
select ':'+ rtrim(str_replace(@mystring,'0',' ')) + ':' union all
select ':'+ str_replace(rtrim(str_replace(@mystring,'0',' ')),' ','0') + ':'
-- and the final solution sans the visual end markers (:)
select str_replace(rtrim(str_replace(@mystring,'0',' ')),' ','0')
go
----------
:0.025000:
: . 25 :
: . 25:
:0.025:
--------
0.025
}
父组件HTML:
import { Component, OnInit } from '@angular/core';
import { ComponentOne } from '...parent-component/component-one.component';
@Component({
selector: 'parent-component',
templateUrl: 'parent-component.component.html',
styleUrls: ['parent-component.component.less']
})
export class ParentComponent implements OnInit {
constructor() {}
buttonOne(): boolean {
this.showComponentOne = true;
}
buttonTwo(): boolean {
this.showComponentTwo = true;
}
ngOnInit() {
}
ngOnDestroy() {
}