如何从组件交互中访问元素?

时间:2019-11-14 12:03:20

标签: angular typescript

我想用background中的条件来更改component interaction

我需要将目标元素与当前元素进行比较。

例如:

<span 
     [style.background]="targetElem == this ? 'red' : '#eee'" 
    (click)="targetElem = $event.target"  >any text ...</span>
<span 
     [style.background]="targetElem == this ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" >any text ...</span>
<span 
     [style.background]="targetElem == this ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" >any text ...</span>
enter code here

如何从component interaction访问元素(this)?

2 个答案:

答案 0 :(得分:0)

您需要做的是从模板中分配一个值,然后将其用于比较。 (click)事件和样式评估在更改检测生命周期中的完全不同的时间发生,所以这是正在进行的事情的一部分。

模板

<span *ngFor="let item of spans"
     [style.background]="targetElem === item ? 'red' : '#eee'"
     (click)="targetElem = item">item.text</span>

代码

spans = [ 
  { text: 'Text 1' },
  { text: 'Text 2' },
  { text: 'Text 3' }
];

targetElem;

答案 1 :(得分:0)

您可以使用#语法将dom元素声明为变量:

<span 
     [style.background]="targetElem == s1  ? 'red' : '#eee'" 
    (click)="targetElem = $event.target"  #s1>any text ...</span>
<span 
     [style.background]="targetElem == s2  ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" #s2>any text ...</span>
<span 
     [style.background]="targetElem == s3  ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" #s3>any text ...</span>

stackblitz中测试