Angular 调用已经存在的组件';另一个组件中的s方法
组件1Angular 调用已经存在的组件';另一个组件中的s方法,angular,typescript,Angular,Typescript,组件1 import { Component } from '@angular/core'; @Component({ selector: 'app-component1', template: ` <button (click)="submit()"></button> ` }) export class Component { constructor() { } someMethod(): void
import { Component } from '@angular/core';
@Component({
selector: 'app-component1',
template:
`
<button (click)="submit()"></button>
`
})
export class Component {
constructor() {
}
someMethod(): void {
}
}
在angular中,没有
行为主体
和事件发射器
,有没有类似的方法?我只想创建一个服务,该服务在另一个组件上有一个句柄,您可以将该组件的参考点传递到:
import { Component } from '@angular/core';
import { ComponentService } from 'filepathofyourcomponentservice';
@Component({
selector: 'app-component2',
template:
`
<p>text</p>
`
})
export class Component2 {
ViewChild('component) component: Component;
constructor(private componentService: ComponentService) {
this.componentService.tapIntoComponent(this.component);
}
}
从'@angular/core'导入{Component};
从“FilePathyOurComponentService”导入{ComponentService};
@组成部分({
选择器:“应用程序组件2”,
模板:
`
正文
`
})
导出类组件2{
ViewChild(‘组件’)组件:组件;
构造函数(私有componentService:componentService){
this.componentService.tapIntoComponent(this.component);
}
}
您可以通过包含组件的父模板将组件A转发到另一个组件B。没有可以查询的组件实例存储库。如果不想使用模板在两者之间进行连接,则必须使用共享服务
app.component.html:
<component-a #refA></component-a>
<component-b [refA]="refA"></component-b>
@Component({...})
export class ComponentA {
public someMethod() { }
}
@Component({...})
export class ComponentB implement OnInit {
@Input() refA: ComponentA;
public ngOnInit() {
if(this.refA) {
this.refA.someMethod();
}
}
}
@组件({…})
导出类组件A{
公共方法(){}
}
@组件({…})
导出类组件B实现OnInit{
@Input()refA:ComponentA;
公共ngOnInit(){
if(this.refA){
this.refA.someMethod();
}
}
}
以上都有缺点
- 如果此表达式在检查错误后已更改,则可以触发错误
- 如果在外部修改组件状态表单,则需要将
中的视图标记为脏视图ComponentA
我不推荐使用上述方法,因为从视图外部改变另一个组件的内部状态是一种反模式。最好使用共享服务和可观察对象。其中可能存在的重复项具有父子关系。但这里没有关系。我需要得到分量2n中分量1的一个瞬间,不,没有。问题中甚至提到:这两个组成部分彼此不相关(兄弟姐妹、父母和子女……)。注意“not”这个词。此外,答案是为您提供一个可能的解决方案;使用共享服务。他需要对实例化组件的引用,而不是新组件。如果是这种情况,他可以使用redux和服务调用现有组件。这些组件之间没有关系
import { Component } from '@angular/core';
import { ComponentService } from 'filepathofyourcomponentservice';
@Component({
selector: 'app-component2',
template:
`
<p>text</p>
`
})
export class Component2 {
ViewChild('component) component: Component;
constructor(private componentService: ComponentService) {
this.componentService.tapIntoComponent(this.component);
}
}
<component-a #refA></component-a>
<component-b [refA]="refA"></component-b>
@Component({...})
export class ComponentA {
public someMethod() { }
}
@Component({...})
export class ComponentB implement OnInit {
@Input() refA: ComponentA;
public ngOnInit() {
if(this.refA) {
this.refA.someMethod();
}
}
}