Mi código,
<modal *ngIf='showModal' [imageValue]="imageId"></modal>Mi componente modelo,
@Component({ selector: 'modal', templateUrl: './app/modal/modal.component.html', providers: [HeaderClass] }) export class ModalComponent { imageValue:any;Quiero obtener el valor de este 'imageValue' pero no sé cómo hacerlo. ¿Puede alguien ayudarme? Gracias.
Si desea enviar datos a la directiva, debe intentarlo así:
Esta es mi directiva personalizada y voy a compartir dos valores del componente o HTML con la directiva.
prueba.directiva.ts:
import { Directive, ElementRef, Input, OnInit } from '@angular/core'; @Directive({ selector: '[input-box]' }) export class TestDirectives implements OnInit { @Input() name: string; @Input() value: string; constructor(private elementRef: ElementRef) { } ngOnInit() { console.log("input-box keys : ", this.name, this.value); } } y ahora se ha creado su directiva y tendrá que agregar esta directiva en su app.module.ts como se muestra a continuación:
aplicación.módulo.ts:
import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { TestDirectives } from '../directives/test.directive'; @NgModule({ declarations: [ AppComponent, TestDirectives ], imports: [], providers: [], bootstrap: [AppComponent] }) export class AppModule { }Deberá usar su directiva en su html y enviar datos a la directiva como en el código a continuación.
Estoy enviando name y value a test.directive.ts .
<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>o
<div input-box [name]="componentObject.name" [value]="componentObject.value"></div>Ahora vea la consola o use los datos en la directiva en consecuencia.
Este es un ejemplo de cómo puede pasar valor a una Directiva
Directiva
import {Directive, Input, HostListener} from '@angular/core'; @Directive({ selector: '[appConfirm]' }) export class ConfirmDirective { //we can also add the attribute directive liek this [appconfirm] if the input in the directive has same name as appConfirm like //@Input() appConfirm:string; and then in component button we can use the directive like //<button type="button" [appConfirm] = "Rahul">Click to Send to Directive</button> @Input() value:string; @HostListener('click',['$event']) confirm(){ const confirmed = window.confirm("Are you Sure ?"); if(confirmed){ window.alert("This is Value ["+this.value+"] Passed by the Component to the Directive") } } constructor() { } }ComponentTemplate.html
<button type="button" appConfirm value = "Rahul">Click to Send to Directive</button>Para obtener más información, consulte este repositorio https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives
Use @input y pase el valor del componente principal, donde se usó este componente como [imgval]="val"