如何从下拉菜单中设置所选文本

时间:2018-12-26 05:03:50

标签: angular typescript angularjs-directive

当我选择一个下拉菜单项时,我需要一个下拉菜单项的文本,很长一段时间以来,我一直没有解决问题的办法。为此,我制定了一个通用指令,以便在使用指令时可以获得所有下拉菜单的文本。这是我的代码

app.component.html

<hello name="{{ name }}"></hello>
<p>
    Start editing to see some magic happen :)
</p>

<div>
    <p>Come from directive: {{selectedText}} </p>
    <p>Come from Parent Component - {{selectedProp}}</p>
    <select [psSelectText]="'selectedText'"  name="selectedProp" [(ngModel)]="selectedProp" >
    <option value=""></option>
    <option *ngFor="let i of arrayList" value="{{i.value}}">{{i.text}}</option>
  </select>
</div>
<br>
<button (click)="hitMe()">Hit me</button>

我的指令:

import { Directive, ElementRef, HostListener, Input, SimpleChanges, OnChanges, Output, EventEmitter, ViewContainerRef } from '@angular/core';
import { NgModel } from '@angular/forms';
import { SelectText } from './select-text.model';

@Directive({
  selector: '[ngModel][psSelectText]',
  providers: [NgModel],
  host: {
    '(ngModelChange)': 'onInputChange($event)'
  }
})
export class PsSelectText implements OnChanges {
  @Input('psSelectText') selectedText: string;
  @Input('ngModel') selectedModel: NgModel;

  constructor(private el: ElementRef, public model: NgModel, private viewContainerRef: ViewContainerRef) { }


  ngOnChanges(changes: SimpleChanges) {
    console.log(this.el)
    if (changes.selectedModel) {
      // this.selectedText.valueAccessor.writeValue(changes.selectedModel.currentValue);
      setTimeout(() => {
        this.viewContainerRef['_view'].component[this.selectedText] =
          this.el.nativeElement.selectedOptions[0].text;
      }, 0);
    }
  }

  onInputChange(event) {
    // Only get selected change
  }
}
  

我已经通过传递一个变量来做到这一点   [psSelectText]="'selectedText'",,但我想传递一个对象   属性selectedText2.text,这里需要将下拉菜单的文本设置为   

将selectedText2.text属性转换为指令。

我的需要,我想这样传递属性:

[psSelectText]="selectedText2.text"

然后将我的指令中的下拉文本设置为此字段selectedText2.text

有什么办法吗?非常感谢。

实际上,需要在此处进行更改:

// "this.selectedText2.text" this property will come from dynamically,
        this.viewContainerRef['_view'].component[this.selectedText2.text] =
          this.el.nativeElement.selectedOptions[0].text;

演示: https://stackblitz.com/edit/angular-dropdown-selected-text

https://angular-dropdown-selected-text.stackblitz.io

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找

  • 将对象而不是文本传递给指令
  • 根据传递的对象(通过指令)在屏幕上分配一个值

请看一下,让我知道这是否是您想要的? https://stackblitz.com/edit/angular-wbu8us

ps-select-text.directive.ts app.component.html 在下面

/* tslint:disable:member-ordering */
import { Directive, ElementRef, HostListener, Input, SimpleChanges, OnChanges, Output, EventEmitter, ViewContainerRef } from '@angular/core';
import { NgModel } from '@angular/forms';
import { SelectText } from './app.component';

@Directive({
  selector: '[ngModel][psSelectText]',
  providers: [NgModel],
  host: {
    '(ngModelChange)': 'onInputChange($event)'
  }
})
export class PsSelectText implements OnChanges {
  @Input('psSelectText') selectedText: SelectText;
  @Input('ngModel') selectedModel: NgModel;

  constructor(private el: ElementRef, public model: NgModel, private viewContainerRef: ViewContainerRef) { }


  ngOnChanges(changes: SimpleChanges) {
    /*
    console.log(this.el);
    console.log(this.selectedText);
    console.log(this.viewContainerRef['_view'].component);
    */
    
    if (changes.selectedModel) {
      // this.selectedText.valueAccessor.writeValue(changes.selectedModel.currentValue);
      setTimeout(() => {

        if (this.selectedText) {
          this.viewContainerRef['_view'].component.selectedText = "(from inside Directive)" + this.selectedText.stText;
        }

        // "this.selectedText" this property will come from dynamically,
          /* 
        this.viewContainerRef['_view'].component[this.selectedText] = 
          this.el.nativeElement.selectedOptions[0].stText;
          */
      }, 0);
    }
  }

  onInputChange(event) {
    // Only get selected change
  }
}


/*
Copyright 2017-2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<hello name="{{ name }}"></hello>
<p>
	Start editing to see some magic happen :)
</p>

<div>
	<p>Come from directive: <mark>{{selectedText}}</mark> </p>
	<p>Come from Parent Component [ngModel]: 
    <span *ngIf="selectedText2"> 
      v: <mark>{{selectedText2.stValue}}</mark> & 
      t: <mark>{{selectedText2.stText}}</mark> 
    </span> 
  </p>
	<select [psSelectText]="selectedText2"  name="selectedProp" [(ngModel)]="selectedText2" >
    <option value=""></option>
    <option *ngFor="let i of arrayList" [ngValue]="i" >{{i.stText}}</option>
  </select>
</div>
<br>
<button (click)="hitMe()">Hit me</button>

答案 1 :(得分:0)

以下代码正在编码

HTML:

function armst(x) {
    var value = parseInt(x, 10),
        rest = value,
        digit,
        sum = 0,
        n = x.toString().length;       // add toString, if a number is entered

    while (rest) {
        digit = rest % 10;
        rest = Math.floor(rest / 10);
        sum += Math.pow(digit, n);    // use it here
    }

    return sum === value
        ? "Armstrong"
        : "Not Armstrong";
}


var num = prompt("Enter a number to check Armstrong"), // try with 54748
    output = armst(num);

console.log("Result is: ", output);

指令:

<hello name="{{ name }}"></hello>
<p>
    Start editing to see some magic happen :)
</p>

<div>
    <p>Come from directive: {{selectedText}} </p>
    <p>Come from Parent Component - {{selectedProp}}</p>
    <select [psSelectText]="'selectedText'"  name="selectedProp" [(ngModel)]="selectedProp" >
    <option value=""></option>
    <option *ngFor="let i of arrayList" value="{{i.value}}">{{i.text}}</option>
  </select>
</div>
<br>
<button (click)="hitMe()">Hit me</button>

组件:

import { Directive, ElementRef, HostListener, Input, SimpleChanges, OnChanges, Output, EventEmitter, ViewContainerRef } from '@angular/core';
import { NgModel } from '@angular/forms';
import { SelectText } from './select-text.model';

@Directive({
  selector: '[ngModel][psSelectText]',
  providers: [NgModel],
  host: {
    '(ngModelChange)': 'onInputChange($event)'
  }
})
export class PsSelectText implements OnChanges {
  @Input('psSelectText') selectedText: string;
  @Input('ngModel') selectedModel: NgModel;

  constructor(private el: ElementRef, public model: NgModel, private viewContainerRef: ViewContainerRef) { }


  ngOnChanges(changes: SimpleChanges) {
    console.log(this.el)
    if (changes.selectedModel) {
      setTimeout(() => {
        this.viewContainerRef['_view'].component[this.selectedText] =
          this.el.nativeElement.selectedOptions[0].text;
      }, 0);
    }
  }

  onInputChange(event) {
    // Only get selected change
  }
}

DEMO