如何将值传递给角度指令 [英] How to pass values to directive in angular

查看:90
本文介绍了如何将值传递给角度指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码,

  <modal *ngIf='showModal' [imageValue]="imageId"></modal>

我的模型组件,

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


export class ModalComponent  {
  imageValue:any;

我想获取此'imageValue'的值,但我不知道该怎么做.任何人都可以帮助我.谢谢.

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.

推荐答案

如果要将数据发送到指令,则应尝试这样操作:

If you want to send data to directive then you should try like this:

这是我的自定义指令,我将共享两个从组件或HTML到该指令的值.

This is my custom directive, and I am going to share two value from component or HTML to the directive.

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中:

and now your directive has been created and you will have add this directive into your app.module.ts like below:

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中使用指令并将数据发送到指令,如下面的代码所示.

我正在将namevalue发送到test.directive.ts.

<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>

<div input-box [name]="componentObject.name" [value]="componentObject.value"></div>

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

Now see the console or use data in the directive accordingly.

这篇关于如何将值传递给角度指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆