我在Component1中具有testTry()函数,该函数接受一个参数并输出值。
export class Component1 implements OnInit {
testTry(name:any){
console.log("Name-->",name);}
ngOnInit(){ }
}
我有一个带有sampleCall()函数的component2,其中我需要通过发送一个参数来调用component1的函数
export class Component2 implements OnInit {
sampleCall(){
let a = "Sravya";
testTry(a);
}
ngOnInit(){ }
}
如何在不涉及HTML的情况下从component1到component2调用函数?
答案 0 :(得分:0)
您可以使用@ViewChild
,
我们可以使用它来控制Child Component
中的Parent Component
。使用它时,我们将获得子组件为 Object
,以便我们能够调用子组件的方法和变量。
Component2.ts
@ViewChild(Component1) component1: Component1;
sampleCall() {
let a = "Sravya";
this.component1.testTry(a);
}
答案 1 :(得分:0)
您可以这样做:
创建服务并将该方法移入服务
将component1
注入component2
中(不推荐)
尝试:
export class Component2 implements OnInit {
constructor(private comp1: Component1){}
sampleCall(){
let a = "Sravya";
this.comp1.testTry(a);
}
ngOnInit(){ }
}
答案 2 :(得分:0)
除了上述在逻辑上正确的解决方案之外,您还可以使用继承(打字稿使用较少的功能)。
将所有功能保存在单独的文件中,例如common-logic.ts
,其他组件只需使用extends
关键字即可访问它们。
export class Component2 extends CommonLogic {}
Component2
export class Component2 implements OnInit extends CommonLogic {
sampleCall(){
let a = "Sravya";
testTry(a);
}
CommonLogic
export class CommonLogic {
testTry(name:any){
console.log("Name-->",name);
}
}
注意:Angular只允许继承最多一层。
答案 3 :(得分:0)
您可以按以下方式使用EventEmmiter。
ChangeService.ts
import {EventEmitter} from 'angular2/core';
export class ChangeService {
calltestTry: EventEmitter<string> = new EventEmitter();
constructor() {}
emitcalltestTryEvent(data) {
this.calltestTry.emit(data);
}
getcalltestTryEmitter() {
return this.calltestTry;
}
}
component1.ts
@Component({
selector: 'app-component1',
})
export class ComponentOne {
item: number = 0;
subscription: any;
constructor(private changeService:ChangeService) {}
ngOnInit() {
this.subscription = this.changeService.getcalltestTryEmitter()
.subscribe(item => this.testTry(item));
}
testTry(item: string) {
console.log(item);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
component2.ts
@Component({
selector: 'app-component2',
})
export class ComponentTwo {
item: number = 0;
subscription: any;
constructor(private changeService:ChangeService) {}
ngOnInit() {
}
sampleCall(item: number) {
let a = "Sravya";
this.changeService.emitcalltestTryEvent(a);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
答案 4 :(得分:0)
实际上有4种方法。
答案 5 :(得分:0)
您可以使用ComponentFactoryResolver来获取组件并使用其属性。
export class Component1 implements OnInit {
testTry(name:any){
console.log("Name-->",name);
}
ngOnInit(){ }
}
import {ViewChild, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
export class Component2 implements OnInit {
@ViewChild('parent', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(
private _cfr: ComponentFactoryResolver
) { }
sampleCall(){
const comp = this._cfr.resolveComponentFactory(Component1);
const component1Ref = this.container.createComponent(comp);
const component1 = component1Ref.instance;
component1._ref = component1Ref;
let a = "Sravya";
component1.testTry(a);
}
ngOnInit(){ }
}