我的代码,
<modal *ngIf='showModal' [imageValue]="imageId"></modal>
我的模型组件,
@Component({
selector: 'modal',
templateUrl: './app/modal/modal.component.html',
providers: [HeaderClass]
})
export class ModalComponent {
imageValue:any;
我希望得到这个&#39; imageValue&#39;的价值。但我不知道怎么做。任何人都可以帮助我。谢谢。
答案 0 :(得分:26)
如果您想将数据发送到指令,那么您应该尝试这样:
这是我的自定义指令,我将从组件或HTML共享两个值到指令。
<强> test.directive.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);
}
}
现在您的指令已经创建,您可以将此指令添加到app.module.ts
中,如下所示:
<强> app.module.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 { }
您必须在html中使用您的指令,并将数据发送到指令,如下面的代码所示。
我将name
和value
发送到test.directive.ts
。
<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>
或
<div input-box [name]="componentObject.name" [value]="componentObject.value"></div>
现在查看控制台或相应地使用指令中的数据。
答案 1 :(得分:2)
这是一个如何将值传递给指令的示例
指令
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>
有关详细信息,请查看此回购https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives
答案 2 :(得分:1)
使用@input并传递父组件中的值,其中使用此组件,如[imgval] =“val”