如何使用事件监听器更新注入

时间:2020-10-19 13:29:10

标签: angular dependency-injection addeventlistener

我正在尝试更新注入中的变量,但仅当我使用间隔时才有效。我想使用一个eventListener。两者都可以调用该函数,但仅在使用间隔时才更改变量。

landing-path.service.ts

import { Injectable, HostListener } from '@angular/core';


//window width
var w = window.innerWidth;

@Injectable({
  providedIn: 'root'
})

export class LandingPathService{
  newpath1 = '13';
  resize;
  load;

  constructor() {this.resize = window.setInterval(() => this.onResize(), 200);/*this.resize = window.addEventListener('resize', this.onResize);*/
}
  
onResize(){
  w = window.innerWidth;
  this.newpath1  = `M0, 0 l${w}, 0 0, 200 -${w}, 0 z`;
  console.log(this.resize);
}
}

landing.component.ts

import { Component, ViewChild, ElementRef, HostListener } from '@angular/core';
import { SubstringService  } from '../substring.service';
import { LandingPathService } from './../landing-path.service';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css'],
  })

export class LandingComponent{
  constructor(readonly ss: SubstringService, 
              readonly lps: LandingPathService
              ) {}
  
  ngAfterViewInit(){
    let pan = (<HTMLInputElement>document.getElementById('svg1'));
    pan.setAttribute('d', `${this.lps.newpath1}`);
  }
  
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    let pan = (<HTMLInputElement>document.getElementById('svg1'));
    pan.setAttribute('d', `${this.lps.newpath1}`);
  }
}

0 个答案:

没有答案