Tra*_*ker 19 typescript angular-directive angular
我的代码,
  <modal *ngIf='showModal' [imageValue]="imageId"></modal>
我的模型组件,
@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})
export class ModalComponent  {
  imageValue:any;
我想获得这个'imageValue'的价值,但我不知道该怎么做.任何人都可以帮助我.谢谢.
Shu*_*rma 31
如果你想将数据发送到指令,那么你应该尝试这样:
这是我的自定义指令,我将从组件或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>
现在查看控制台或相应地使用指令中的数据.
这是一个如何将值传递给指令的示例
指示
    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() { }
}
组件模板.html
<button type="button" appConfirm value = "Rahul">Click to Send to Directive</button>
有关更多信息,请查看此 repo https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives
| 归档时间: | 
 | 
| 查看次数: | 29934 次 | 
| 最近记录: |