基于组件Angular 2的调用函数

时间:2018-02-10 13:10:43

标签: angular

我有三个组件(个人资料,页面,群组),每个组件都称为<app-posts [data]="post"></app-posts>,而在我的posts.component.html我有<a>个标记:

<a id="load-more-button" (click)="myQuestion()">Load More</a>

我想根据我现在所在的组件替换myQuestion()函数,如果我在个人资料中,我希望myQuestion()myProfile(),与页面和组相同

我想为每个组件提供服务并每次检查我是谁,但在我看来,它是愚蠢的方式,任何想法?

3 个答案:

答案 0 :(得分:0)

这样做的正确方法就是传递一个属性值,让您的组件知道当前上下文中的行为应该是什么。并取决于你myQuesition()内部的句柄。

因此,在3个地方,您会向组件传递不同的值:

<app-posts [data]="post" [profile]="'question'"></app-posts>
<app-posts [data]="post" [profile]="'profile'"></app-posts>
<app-posts [data]="post" [profile]="'question'"></app-posts>

您的观点:

 <a id="load-more-button" (click)="question()">Load More</a>

在您的posts.component.ts

export class FriendComponent {
    @Input() funcType: string = 'profile';

    constructor() {}

    question(){
        if(this.funcType === 'profile'){
           this.myQuestion();
         } else if (this.funcType === 'question'){
           this.myProfile();
         }
    }
}

答案 1 :(得分:0)

您可以绑定组件本身的功能地址

<强> component.ts

export default class MyComponent {
    //myFunctionAdress = /** assign function based on component**/;
    //example:
    myFunctionAdress = this.myFuncion;

    myFunction() {

    }
}

<强> component.html

<a (click)="myFunctionAdress()">Load More</a>

答案 2 :(得分:0)

posts.component.ts

posts.component.ts中定义名为@Output()的{​​{1}}绑定。每次用户点击链接时,loadMore都会发出并将此事件委托给其父组件(页面,组,个人资料)

event

个人资料,页面,群组件。

在您的父组件中,收听@Component({ selector: 'app-posts', template: ` <a id="load-more-button" (click)="loadMore.emit()">Load More</a> `, styleUrls: ['./app.component.css'] }) export class PostsComponent { @Input() data: any; @Output() loadMore: EventEmitter<any> = new EventEmitter(); } 个事件。

例如个人资料:

loadMore

@Component({ selector: 'app-profile', template: ` <app-posts [data]="profiles" (loadMore)="onLoadMoreProfiles()"></app-posts> `, styleUrls: ['./app.component.css'] }) export class ProfileComponent { profiles: any onLoadMoreProfiles() { // load more profile or whatever } } group.component.ts

重复此模式

有关详细信息,请查看官方文档https://angular.io/guide/component-interaction#parent-listens-for-child-event