supertonsky
supertonsky

Reputation: 2743

In Angular, how do I expose a variable from a parent component to a child component?

Suppose I have a component in which the user of this component can embed its own contents and access the variable the parent is exposing.

Say I have the following parent component template

    @Component({
      selector: 'parent',
      template: `<ng-container>
                  <ng-content [select]="content"></ng-content>
                </ng-container>`
    )}

Here is an example of how the component will be used.

    <parent>
      <div content>
        <button (click)="x.close()"></button>
      </div>
    </parent>

I need to have x variable exposed to the user of the component. How do I do this in Angular?

The reason I want to do this is because the parent must not know anything about the child component it is going to contain that's why I thought of just exposing a variable. In this way, only child needs to be aware about the parent but not vice-versa.

Upvotes: 1

Views: 621

Answers (1)

JsNgian
JsNgian

Reputation: 835

If you are trying to access a variable from the parent component you can use Template variable reference(#) in html. Please refer below.

    @Component({
      selector: 'parent',
      template: `<ng-container>
                  <ng-content [select]="content"></ng-content>
                </ng-container>`
    )}
    export class ParentConteinr {
      x = {
         close: () => { // code to close }
      }
    }
    <parent #parent>
      <div content>
        <button (click)="parent.x.close()"></button>
      </div>
    </parent>

Upvotes: 2

Related Questions