如何在 Angular 中使用 ViewChild 而不是 querySelector?

如何解决如何在 Angular 中使用 ViewChild 而不是 querySelector?

我是 Angular 的新手。我使用 querySelector 滚动到组件中的特定片段。但它在不同的浏览器中表现不同。我发现如果我使用 ViewChild 重写同样的东西,那么它可能会正常运行。 ts 文件中的 newScroll 函数使用的是 querySelector。如何使用 ViewChild 而不是 querySelector 重写它?

这是我的 service.component.ts 文件。


  import { AfterContentChecked,AfterContentInit,AfterViewInit,Component,OnDestroy,OnInit } from '@angular/core';
  import { ActivatedRoute,NavigationEnd,Router } from '@angular/router';
  import { environment } from 'src/environments/environment';
  import { delay,filter } from 'rxjs/operators';
  @Component({
  
    selector: 'app-serviepage',templateUrl: './serviepage.component.html',styleUrls: ['./serviepage.component.scss']
  })
  export class ServiepageComponent implements OnInit,AfterContentChecked,AfterContentInit {
    env = environment;
    fragment
    subscripti
    isInitDone = false
    constructor(private activatedRoute: ActivatedRoute,private router: Router) {
    }
  
  
    ngOnInit(): void {
      this.activatedRoute.fragment.subscribe(res => {
        console.log('res',res);
        this.fragment = res;
        this.newScroll();
      });
    }
  
  
    ngAfterViewInit(): void {
      //console.log('ngAfterViewInit')
      this.isInitDone = true
    };
  
    newScroll(){
      if(!this.fragment){
        return;
      }
      try {
        document.querySelector('#' + this.fragment).scrollIntoView();
        this.fragment = '';
      } catch (e) { }
    }
    ngAfterContentChecked(): void {
      //Called after every check of the component's or directive's content.
      //Add 'implements AfterContentChecked' to the class.
      //console.log('ngAfterContentChecked')
    }
  
    ngAfterContentInit(): void {
      //Called after ngOnInit when the component's or directive's content has been initialized.
      //Add 'implements AfterContentInit' to the class.
      // // console.log('ngAfterContentInit')
      // this.subscription = this.router.events.pipe(
      //   filter(event => event instanceof NavigationEnd)
      // ).subscribe((event: NavigationEnd) => {
      //   //if (this.isInitDone) {
      //   this.checkScroll()
  
      //   //}
      // });
    }
    ngOnDestroy() {
      // this.subscription.unsubscribe();
    }
  
    // checkScroll() {
    //   this.fragment = this.activatedRoute.snapshot.fragment
    //   if (!!this.fragment) {
    //     this.scroll(this.fragment)
    //   }
    // }
  
    // scroll(id) {
    //   console.log('exactId',id)
    //   if(!id){
    //     return;
    //   }
    //   const elmnt = document.getElementById(id);
    //   elmnt.scrollIntoView({ behavior: "smooth",block: "start",inline: "nearest" });
    // }
  
  }```

This is my service.component.html
 <div class="bannerServices">
    <!--<h1 class="bannerHeading">OUR SERVICES</h1>-->
</div>
<div class="tagline">
    <p>Check Out Some of Our professional Collections</p>
</div>
<div class="serviceSection">
    <div class="ContentSection" id="customer-service">
        <div class="contentImage customer">
            <!--<img src="{{env.assetsPath}}assets/img/seviceImages/Connaught-Navy.jpg" alt="">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Busso-Waistcoat---Navy.jpg" alt="">-->
            <img src="{{env.assetsPath}}assets/img/logo/customer.jpg" alt="">
        </div>
        <div class="ContentText">
            <div>
                <h1>CUSTOMER SERVICE </h1>
                <p>TWC pride themselves on delivering a first class service,using high quality products while providing
                    a flexibility that is second to none. No order is too big or too small; all orders are important to
                    us! Our dedicated team apply their extensive knowledge of our products to assist you with your
                    uniform requirements,offering advice on how to obtain your ideal look and dealing with queries or
                    issues quickly and efficiently. Our team work closely together,ensuring that you have continuity in
                    your care and everyone has a clear understanding of your requirements. Our friendly approach enables
                    us to build relationships with our clients,making us an extension or your business,and making you
                    a part of our extended family. As part of our initial consultancy,we have introduced the use of
                    ‘mood boards’ to give our clients an idea of what options are available to them with regards to
                    colour combinations,styles,branding,etc. We also provide a sampling service where you can trial a
                    style to suit your needs.
                </p>
                <!--<div>
                    <a href="">Learn More</a>
                </div>-->
            </div>
        </div>
    </div>
    <div class="ContentSection" id="tailoring-and-alterations">
        <div class="contentImage content-order-2">
            <img src="{{env.assetsPath}}assets/img/seviceImages\Cassino-Jkt-Mid-blue.jpg" alt="">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Cassino Marino Double.jpg" alt="">
        </div>
        <div class="ContentText ContentSectionplue content-order-1">
            <div class="ContentSectionplue">
                <h1>TAILORING AND ALTERATIONS </h1>
                <div>Measuring and Fitting Service</div>
                <br>
                <p>
                    At TWC we have always had a measuring and fitting service for our clients. This service is free of
                    charge and is adapted to the individual needs of our client to ensure all body sizes and shapes are
                    accounted for. Our experience and knowledge allows our Account Manager to individually recommend a
                    suitable style and cut as part of this in-house measuring and tailoring service. We can also arrange
                    for samples and alterations to ensure that you achieve a look that enhances your image.
                </p>
                <!--<div>
                    <a href="">Learn More</a>
                </div>-->
            </div>
        </div>
    </div>
    <div class="ContentSection" id="branding">
        <div class="contentImage">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Connaught-Navy.jpg" alt="">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Prosecco Blouse-Pink.jpg" alt="">
        </div>
        <div class="ContentText">
            <div>
                <h1>BRANDING</h1>
                <div class="subh1">Heatseal Printing</div><br>
                <p>An alternative to embroidery; heat seal application is an ideal option for larger images,especially
                    those on the backs of outerwear garments. As heat seal transfers do not puncture fabrics,it is a
                    perfect option for waterproof garments. They are also suitable for cotton garments. Available in an
                    array of colours,heat seal transfers can withstand regular washing without peeling,making heat
                    seal printing an ideal choice for your branding. As with embroidered logos,TWC have the facility to
                    apply heat seal transfers in-house,keeping the production of your garments all under one roof and
                    ensuring a speedy turnaround of your order.
                </p>
                <br>
                <div class="subh1">Tax Tabbing</div>
                <br>
                <p>By opting for our tax tabbing service,you legally transform your clothes into your uniform thus
                    providing you with possible tax allowances. A tax tab is a woven fabric label that is added
                    externally onto the garment to show that it is uniform. These are produced with your logo and as
                    well as offering potential financial benefits can also be a more subtle and discrete way of branding
                    your garments.</p>

                <br>
                <div class="subh1">Embroidery</div>
                <br>
                <p>
                    TWC know that a branded garment enhances the presence of your company. Branding garments can also
                    provide a sense of belonging for your employees. We can easily add your corporate identity to any
                    garments required. Whether you have an existing logo are you want to design a new compilation we ca
                    digitise and apply this to almost any garment with our in-house embroidery. Once the design has been
                    approved,we will apply the logo to your garments. Embroidery is best suited to smaller less
                    intricate images.

                </p>
                <!-- <div>
                    <a href="">Learn More</a>
                </div>-->
            </div>
        </div>
    </div>
    <div class="ContentSection" id="delivery-and-distribution">
        <div class="contentImage content-order-2 transport">
            <!--<img src="{{env.assetsPath}}assets/img/seviceImages/Cassino-Jkt-Mid-blue.jpg" alt="">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Connaught-Navy.jpg" alt="">-->
            <img src="{{env.assetsPath}}assets/img/seviceImages/transport.png" alt="">

        </div>
        <div class="ContentText ContentSectionplue content-order-1 transport">
            <div class="ContentSectionplue">
                <div id=""></div>
                <h1>DELIVERY AND DISTRIBUTION </h1>
                <p>TWC has an inhouse delivery service that allows us to ensure that all our garments are delivered in a
                    pristine condition. This service is provided free of charge. All TWC garments are ‘man packed’ using
                    marked packaging. All of our suits are provided with a high quality complimentary branded zip bag.
                    Packaging is individually labelled with the wearers name and the site that they are located. We do
                    not charge for our deliveries as we believe this should be part our service provision,in addition
                    any collection of garments requiring alterations,exchanges or refunds are also provided free of
                    cost. Local deliveries are made by our TWC drivers who adhere to our high standards of courtesy and
                    customer service. In line with our customer care and quality procedures all orders are delivered to
                    sites/clients as per your instruction. Your orders can be delivered to a specified location,for
                    example,control room,or loading bay where a signature is obtained from the person receiving and
                    acknowledging the delivery. National deliveries are made by our courier company who also acquire a
                    signature from the receivers. Once a delivery has been made customers will receive an
                    acknowledgement via email or text providing an update on the status of their delivery.
                </p>
                <!--<div>
                    <a href="">Learn More</a>
                </div>-->
            </div>
        </div>
    </div>
    <!--<div class="ContentSection">
        <div class="contentImage">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Connaught-Navy.jpg" alt="">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Prosecco Blouse-Pink.jpg" alt="">
        </div>
        <div class="ContentText">
            <div>
                <h1>OUTERWARE </h1>
                <p>Lorem ipsum,dolor sit amet consectetur adipisicing elit. Nemo voluptate ab explicabo,enim eum,repellat
                    deleniti nam expedita accusantium,quam ullam ut. Dolorem fugit maxime incidunt exercitationem 1500
                </p>
                <div>
                    <a href="">Learn More</a>
                </div>
            </div>
        </div>
    </div>
    <div class="ContentSection">
        <div class="contentImage content-order-2">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Aldwych-Navy.jpg" alt="">
            <img src="{{env.assetsPath}}assets/img/seviceImages/Cassino-Jkt-Mid-blue.jpg" alt="">
        </div>
        <div class="ContentText ContentSectionplue content-order-1">
            <div class="ContentSectionplue">
                <h1>CONCEPT </h1>
                <p>Lorem ipsum,quam ullam ut. Dolorem fugit maxime incidunt exercitationem 1500
                </p>
                <div>
                    <a href="">Learn More</a>
                </div>
            </div>
        </div>
    </div>-->
</div>
<!--<div class="servicefooter">
    <div class="servicefooterContent">
        <div class="heading2">
            <div fxLayout="column" fxLayoutAlign="start start" fxLayoutGap="8pt">
                <h1>Why TWC?</h1>
                <div class="lineH1"></div>
            </div>
        </div>
        <p>Lorem ipsum dolor sit amet consectetur,adipisicing elit. Nam quibusdam,iste numquam praesentium sint,nulla
            quasi,cum nemo totam quia porro voluptates alias possimus vero reiciendis eum nostrum eveniet reprehenderit
            maxime? Neque architecto asperiores velit dolor molestias expedita illo blanditiis! Quae obcaecati accusamus
            velit hic voluptas architecto,ex quaerat ipsam.
        </p>
    </div>
</div>-->
<app-top-brands></app-top-brands> ```

提前致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res