创建自定义的社交分享按钮在Angular中

huangapple go评论69阅读模式
英文:

Create Custom Social Share Buttons in angular

问题

I will provide a translation of the content you provided:

我会提供你提供的内容的翻译:

I will appreciate any ideas and support for this issue
我将感激对这个问题的任何想法和支持

I have an angular project and I try to create icons share buttons for social media.
我有一个Angular项目,我尝试创建用于社交媒体分享的图标按钮。

I have a component named landing.component. in the HTML file I implemented a Modal popup to allow showing a new windows where I have the icons. Please, follow screenshots below
我有一个名为landing.component的组件。在HTML文件中,我实现了一个模态弹窗,以便显示一个新窗口,其中包含这些图标。请查看下面的截图。

创建自定义的社交分享按钮在Angular中
创建自定义的社交分享按钮在Angular中

Below, is the new windows
下面是新窗口

创建自定义的社交分享按钮在Angular中
创建自定义的社交分享按钮在Angular中

the HTML code is here
这里是HTML代码

(以下是HTML代码部分)

In the facebook option, I created a variable #facebook that will allow me to use viewchildren in the ts file to do an elementref and find the element in the DOM.
在Facebook选项中,我创建了一个变量#facebook,这将允许我在ts文件中使用viewchildren来执行elementref并查找DOM中的元素。

In the viewchildren option, I created a variable link1.
在viewchildren选项中,我创建了一个变量link1。

then, in the ngAfterViewInit I created two variables url and title. the url variable will take the link of my page to be share and the title is just a message.
然后,在ngAfterViewInit中,我创建了两个变量url和title。url变量将获取我的页面链接以供分享,而title只是一条消息。

Finally, I used this command:
最后,我使用了这个命令:

(以下是命令部分)

The code is not working, basically when I click the Facebook icon, it only closes the window and that's it, and the web shows me this error here below:
代码不起作用,基本上当我点击Facebook图标时,它只是关闭窗口,就是这样,网页显示我下面的错误:

(以下是错误截图部分)

the landing.component.ts code is here below:
landing.component.ts代码如下:

(以下是代码部分)

I really appreciate any help.
我非常感激任何帮助。

英文:

I will appreciate any ideas and support for this issue

I have an angular project and I try to create icons share buttons for social media.
I have a component named landing.component. in the HTML file I implemented a Modal popup to allow showing a new windows where I have the icons. Please, follow screenshots below

创建自定义的社交分享按钮在Angular中

Below, is the new windows

创建自定义的社交分享按钮在Angular中

the HTML code is here

<div class="card-wrapper" fxLayout="row wrap" fxLayoutAlign="start start">
  <div
    class="card active-card"
    fxFlex="25"
    *ngFor="let category of categories"
    (click)="categoryClick(category)"
  >
    <picture>
      <img [src]="category.imageLocation" />
    </picture>
    <div class="card-overlay" fxLayout="row wrap" fxLayoutAlign="center end">
      <span class="card-title" fxFlex="100">{{ category.title }}</span>
      <div class="card-buttons" fxFlex="100" fxLayout="row">

        <ul class="list-inline text-center member-icons ">
          <li class="list-inline-item">
            <button mat-icon-button disableRipple class="btn btn-primary" routerLink="/mtl"  (click)="open(content)"><i class="fa-solid fa-share"></i></button>
          </li>
          <span fxFlex></span>
        </ul>

        <!-- <button mat-icon-button disableRipple>
          <heart-icon></heart-icon>
        </button> -->
        <!-- <span fxFlex></span> -->
        <!-- <button mat-icon-button disableRipple> -->
          <!-- <download-icon></download-icon> -->
       <!--  </button> -->
      <!--   <button mat-icon-button disableRipple>
          <share-icon></share-icon>
        </button> -->
      </div>
    </div>
  </div>
</div>

<section
  class="cragcity-container p-t-5"
  fxLayout="row"
  fxLayoutAlign="space-between start"
>
  <div style="margin: auto">
    <img class="socmed-icon m-r-15" src="./assets/icons/facebook.webp" />
    <img class="socmed-icon m-r-15" src="./assets/icons/skype.webp" />
    <img class="socmed-icon" src="./assets/icons/instagram.webp" />
  </div>
</section>


<ng-template #content let-modal>
	<div class="modal-header">
		<h4 class="modal-title" id="modal-basic-title">Share Social Media</h4>
		<button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
	</div>
	<div class="modal-body">


    <form>
			<div class="mb-3">
				<label for="Social Media"></label>

        <div class="share-btn-container">
          <a #facebook href="#" class="facebook-btn">
            <i class="fab fa-facebook"></i>
          </a>
          <a href="#" class="twitter-btn">
            <i class="fab fa-twitter"></i>
          </a>

          <a href="#" class="pinterest-btn">
            <i class="fab fa-pinterest"></i>
          </a>

          <a href="#" class="linkedin-btn">
            <i class="fab fa-linkedin"></i>
          </a>

          <a href="#" class="whatsapp-btn">
            <i class="fab fa-whatsapp"></i>
          </a>
        </div>
				<!-- <div class="input-group">
					<input

						name="dp"
						ngbDatepicker
						#dp="ngbDatepicker"
					/>
					<button class="btn btn-outline-secondary bi bi-calendar3" (click)="dp.toggle()" type="button"></button>
				</div> -->
			</div>
		</form>


	</div>
	<div class="modal-footer">
		<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Close</button>
	</div>
</ng-template>

<app-cragcity-footer></app-cragcity-footer>

In the facebook option, I created a variable #facebook that will allow me to use viewchildren in the ts file to do an elementref and find the element in the DOM.
In the viewchildren option, I created a variable link1.

then, in the ngAfterViewInit I created two variables url and title. the url variable will take the link of my page to be share and the title is just message.
Finally, I used this command:

this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)

(this is what I believe is the same in js document.location.href) but used in ts

The code is not working, basically when I click the facebook icon only close the windows and that's it and the web shows me this error here bbelwo:

创建自定义的社交分享按钮在Angular中

the landing. component.ts code is here below:

import { Component, OnInit, Input, ViewChild, ElementRef, AfterViewInit, ViewChildren } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DataService } from 'src/app/core/services/data.service';
import { category } from '../models/category';

import { ModalDismissReasons, NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.scss']
})
export class LandingComponent implements OnInit, AfterViewInit {

  public categories = new Array<category>();
  @Input() name;

  url:string;
  title:string;

  closeResult: string | undefined;


  constructor(private _dataService: DataService, private router: Router, private modalService: NgbModal, private route: ActivatedRoute) {

  }


  ngOnInit(): void {
    this.retrieveCategories();
  }

  @ViewChildren("facebook")link1: ElementRef;


  ngAfterViewInit() {

    this.url = this.router.url;
    /* this.link1.nativeElement = this.url; */

    this.title = encodeURI("Facebook");


    this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)
    /* console.log(this.link1);
    console.log(this.url);
 */
    /* this.link1.nativeElement.setAttribute('xlink:href') */
  }


  retrieveCategories() {
    const actionUrl = 'v1/category';
    const params = {};
    this._dataService.get<any>(actionUrl, params)
      .subscribe(data => {
        if (data !== null) {
          if (!data.isError) { this.categories = data.result; }
        }
      });
  }

  categoryClick(data: category) {
    if (data.subCategory.length > 0)
      this.router.navigate(['mtl', data.id]);
  }

  open(content) {
		this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then(
			(result) => {
				this.closeResult = `Closed with: ${result}`;
			},
			(reason) => {
				this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
			},
		);
	}

  private getDismissReason(reason: any): string {
		if (reason === ModalDismissReasons.ESC) {
			return 'by pressing ESC';
		} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
			return 'by clicking on a backdrop';
		} else {
			return `with: ${reason}`;
		}
	}

}

I really appreciate any help

Regards

答案1

得分: 1

以下是翻译好的部分:

首先,@ViewChild@ViewChildren 之间有一个区别。前者将查找一个元素,而后者将查找多个元素。所以在您的情况下,使用 @ViewChild("facebook") link1: any;

但更好的方法是让 Angular 完成这项工作,而不要使用 setAttribute 来操作原生元素。这样,您可以像这样绑定任何内容到 href 属性:

HTML

<a #facebook [href]="facebookLink" class="facebook-btn">
  <i class="fab fa-facebook"></i>
</a>

代码

facebookLink: string = "https://facebook.com";

您还可以使用 ngFor 循环生成链接,以获得更大的灵活性。

代码

linkObjects = [
  { iconClassI: "fab fa-facebook", iconClassA: "facebook-btn", link: "http://facebook.com" },
  {... 其他所有链接}
]

HTML

<div class="share-btn-container">
  <a *ngFor="let item of linkObjects" [href]="item.link" [class]="item.iconClassA">
    <i [class]="item.iconClassI"></i>
  </a>
</div>

希望这有帮助。如果您有任何其他问题,请随时提问。

英文:

First it is a different between @ViewChild and @ViewChildren. The first will search one element, the second multiple elements. So in your case use @ViewChild(&quot;facebook&quot;) link1: any;

But a better approach is to let Angular do this thing and don't use setAttribute to the native element. So you can bind anything to the href attribute like this:

HTML

&lt;a #facebook [href]=&quot;facebookLink&quot; class=&quot;facebook-btn&quot;&gt;
  &lt;i class=&quot;fab fa-facebook&quot;&gt;&lt;/i&gt;
&lt;/a&gt;

Code

facebookLink: string = &quot;https://facebook.com&quot;;

You can generate the links with a ngFor loop, too for more flexibility.

CODE

linkObjects = [{iconClassI: &quot;fab fa-facebook&quot;, iconClassA: &quot;facebook-btn&quot;, link: &quot;http://facebook.com&quot;}, {... all other links}]

HTML

&lt;div class=&quot;share-btn-container&quot;&gt;
  &lt;a *ngFor=&quot;let item of linkObjects&quot; [href]=&quot;item.link&quot; [class]=&quot;item.iconClassA&quot;&gt;
    &lt;i [class]=&quot;item.iconClassI&quot;&gt;&lt;/i&gt;
  &lt;/a&gt;
&lt;/div&gt;

huangapple
  • 本文由 发表于 2023年2月14日 01:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定