如何将值传递给angular中的指令

Tra*_*ker 19 typescript angular-directive angular

我的代码,

  <modal *ngIf='showModal' [imageValue]="imageId"></modal>
Run Code Online (Sandbox Code Playgroud)

我的模型组件,

@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})


export class ModalComponent  {
  imageValue:any;
Run Code Online (Sandbox Code Playgroud)

我想获得这个'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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您的指令已经创建,您将在下面添加此指令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 { }
Run Code Online (Sandbox Code Playgroud)

您必须在html中使用您的指令并将数据发送到指令,如下面的代码所示.

我派namevaluetest.directive.ts.

<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>
Run Code Online (Sandbox Code Playgroud)

要么

<div input-box [name]="componentObject.name" [value]="componentObject.value"></div>
Run Code Online (Sandbox Code Playgroud)

现在查看控制台或相应地使用指令中的数据.


Rah*_*ngh 5

这是一个如何将值传递给指令的示例

指示

    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() { }

}
Run Code Online (Sandbox Code Playgroud)

组件模板.html

<button type="button" appConfirm value = "Rahul">Click to Send to Directive</button>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看此 repo https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives


Rem*_*yaJ 2

使用@input并传递来自父组件的值,该组件的使用方式如下[imgval]="val"