Home > Mobile >  How do I send the Child Content from a Reusable Component using @Input
How do I send the Child Content from a Reusable Component using @Input

Time:12-06

Using Angular 12.

I want to create a re-usable button component. I want to get the text inside the tags of where I host my component and then get it as an Input inside my component.

Inside my home.component.html:

<app-ui-text-button color="#fe7f2d">Press Me!</app-ui-text-button>

I want to get Press Me! text and send it as an Input to my component.

My Component:

@Component({
    selector: 'app-ui-text-button',
    styles: [`
            .button {
                padding: 12px 8px;
                border-radius: 5px;
                cursor: pointer;
            }
            .button:hover {
                filter: brightness(1.2);
            }
        `],
    template: `
        <div  [style.backgroundColor]="color" (click)="onClick($event)">{{ text }}</div>
    `
}
)
export class AppUiTextButtonComponent {

    // Inputs
    @Input() text = 'sdfs';
    @Input() color = '#619b8a';
    // @Input() childContent: ElementRef<any> = new ElementRef(any);

    // Outputs
    @Output() clicked = new EventEmitter<any>();

    onClick(event: Event) {
        this.clicked.emit(event);
    }
}

So I want to grab the text and insert it as dynamic variable inside my div.

I have tried

@Input() childContent: ElementRef<any> = new ElementRef(any);
@Input() text = '';

wihtout success. I also tried to search online, but not getting any clear answers.

Thank you in advance.

CodePudding user response:

Method 1: simple method

if you want the text in your custom component. you can do it as

<app-ui-text-button color="#fe7f2d" [text]="Press Me!"></app-ui-text-button>

then text @Input will have Press Me! in your component!

Method 2: using content projection

ui-text-button.component.ts

@Component({
    selector: 'app-ui-text-button',
    styles: [`
            .button {
                padding: 12px 8px;
                border-radius: 5px;
                cursor: pointer;
            }
            .button:hover {
                filter: brightness(1.2);
            }
        `],
    template: `
        <div  [style.backgroundColor]="color" (click)="onClick($event)">
<ng-content></ng-content> <!-- here added this ng-content tag -->
</div>
    `
}
)
export class AppUiTextButtonComponent {

    // Inputs
   // @Input() text = 'sdfs'; // don't need this anymore with content projection
    @Input() color = '#619b8a';
    // @Input() childContent: ElementRef<any> = new ElementRef(any);

    // Outputs
    @Output() clicked = new EventEmitter<any>();

    onClick(event: Event) {
        this.clicked.emit(event);
    }
}

now using this ui-text-button as you want to use in your example

<app-ui-text-button color="#fe7f2d">Press Me!</app-ui-text-button>

  • Related